Why does my redirects() in NextJS not work? - redirect

what am I doing wrong? I'm building an accessible website with NextJS and want to redirect to fitting pages to the plain-language-counterpart. But since they are a different kind of language, their URLs are different, too.
My routes are built like this:
Standard language = my-website.com/about
Plain language = my-website.com/plain-language/about
And I have a switch where I can just change the /plain-language/ part
Now I have these routes:
my-website.com/accessible-webdesign
my-website.com/plain-language/for-disabled-persons
And if I click the switch on the first one, it will link me to my-website.com/plain-language/accessible-webdesign, which doesn't exist! So I used redirects() and also restarted my server to fix this, but it doesn't work. It doesn't redirect and I get a 404 just as before.
Can you check my code and tell me, what I should change to make it work?
Thank you!
This is my next.config.js:
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
/** #type {import('next').NextConfig} */
const path = require('path');
const withPWA = require('next-pwa')({
dest: 'public',
disable: process.env.NODE_ENV === 'development',
sw: 'sw.js'
})
const nextConfig = {
async redirects(){
return[
{
source: '/plain-language/accessible-webdesign',
destination: '/plain-language/for-disabled-persons',
permanent: 'true'
}
]
},
reactStrictMode: true,
swcMinify: true,
trailingSlash: false,
webpackDevMiddleware: config => {
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300
}
return config
},
sassOptions: {
includePaths: [path.join(__dirname, 'styles')]
},
experimental: {
images: {
layoutRaw: true
}
},
images: {
/*unoptimized: true - for static export!*/
/*deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
formats: ['image/webp']*/
}
}
module.exports = withBundleAnalyzer(withPWA({nextConfig}));

My working solution was from here: https://stackoverflow.com/a/58182678/
I put a middleware.ts in the root-folder (right next to package.json, next.config.js etc).
And I wrote this inside:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export async function middleware(request: NextRequest) {
/* /accessible-webdesign --> /for-disabled-persons */
if (request.nextUrl.pathname.startsWith('/plain-language/accessible-webdesign')) {
return NextResponse.redirect(new URL('/plain-language/for-disabled-persons', request.url));
}
/* /another-url --> /another-redirect */
if (request.nextUrl.pathname.startsWith('/plain-language/another-url')) {
return NextResponse.redirect(new URL('/plain-language/another-redirect', request.url));
}
}
Not as beautiful, but working.

Related

Redirect Strapi admin index to admin login

I am currently looking for way to create a permanent 301 redirect from the default Strapi admin index route (ie strapidomain.com) to the configured admin route (ie strapidomain.com/admin).
I have explored utilizing a custom middleware by configuring the admin package:
Path: ./admin/middlewares/redirect/index.js
const path = require('path');
module.exports = strapi => {
return {
initialize: function(cb) {
strapi.router.get('/', (ctx) => {
ctx.redirect(strapi.config.get('server.admin.url', '/admin'))
});
}
};
};
I then activated the custom middleware with:
Path: ./admin/config/middleware.js
module.exports = {
settings: {
redirect: {
enabled: true
}
}
}
Unfortunately I can still hit the admin panel route without being redirected. Based on everything I have read, this should be possible however I have not been able to get this working.
Thoughts?
for newer version v4+
src/middlewares/redirector.js
module.exports = (config, {strapi}) => {
return async (ctx, next) => {
if (ctx.path === '/') {
ctx.redirect(strapi.config.get('server.admin.url', '/admin'));
return
}
await next()
};
};
config/middlewares.js
module.exports = [
{name: 'global::redirector'},
//...
]
The only issue here is that you just placed the redirect middleware within a admin folder which was absolutely not required. The middlewares folder should directly reside at the root of your project.
Correct the path from:
./admin/middlewares/redirect/index.js
To this:
./middlewares/redirect/index.js
I can show you what I've tried personally, below:
My implementation:
1. Create a directory in the root of your project
$ mkdir -p ./middlewares/redirector/
2. Create a index.js file in ./middlewares/redirector/ with the content as:
module.exports = () => {
return {
initialize() {
strapi.router.get('/', (ctx) => {
ctx.redirect(strapi.config.get('server.admin.url', '/admin'));
});
},
};
};
3. Finally enable the redirector middleware in the config/middleware.js file:
module.exports = {
settings: {
redirector: {
enabled: true,
},
},
};

Vscode language server extension connection.onCompletion

I am creating a language server. Specifically, the issue is with completions. I'm returning a big list of completion items but whenever I test my language the completion provider simply will not suggest anything after I type a dot(.) when I'm expecting it to suggest, essentially, class members associated with the symbol left of said dot(.). Don't get me wrong, suggestions work until I type the dot(.) character and then it says, "No Suggestions".
Also, I'm trying to implement this server side and not client side.
EDIT:
Essentially, I'm assembling a big list and returning it.
connection.onInitialize((params: node.InitializeParams) => {
workspaceFolder = params.workspaceFolders![0].uri;
const capabilities = params.capabilities;
// Does the client support the `workspace/configuration` request?
// If not, we fall back using global settings.
hasConfigurationCapability = !!(
capabilities.workspace && !!capabilities.workspace.configuration
);
hasWorkspaceFolderCapability = !!(
capabilities.workspace && !!capabilities.workspace.workspaceFolders
);
hasDiagnosticRelatedInformationCapability = !!(
capabilities.textDocument &&
capabilities.textDocument.publishDiagnostics &&
capabilities.textDocument.publishDiagnostics.relatedInformation
);
capabilities.workspace!.workspaceEdit!.documentChanges = true;
const result: node.InitializeResult = {
capabilities: {
textDocumentSync: node.TextDocumentSyncKind.Incremental,
colorProvider: true,
hoverProvider: true,
definitionProvider: true,
typeDefinitionProvider: true,
referencesProvider: true,
documentHighlightProvider: true,
documentSymbolProvider: true,
workspaceSymbolProvider: true,
// codeActionProvider: true,
codeLensProvider: {
resolveProvider: true,
workDoneProgress: false
},
// Tell the client that this server supports code completion.
completionProvider: {
resolveProvider: true,
workDoneProgress: false,
triggerCharacters: ['.', '/'],
allCommitCharacters: ['.']
},
signatureHelpProvider: {
triggerCharacters: ['('],
retriggerCharacters: [','],
workDoneProgress: false
},
executeCommandProvider: {
commands: ["compile"],
workDoneProgress: false
},
semanticTokensProvider: {
documentSelector: [{ scheme: 'file', language: 'agc' }],
legend: {
tokenTypes: gTokenTypes,
tokenModifiers: gTokenModifiers
},
full: true,
workDoneProgress: false
}
}
};
if (hasWorkspaceFolderCapability) {
result.capabilities.workspace = {
workspaceFolders: {
supported: true
}
};
}
return result;
});
// This handler provides the initial list of the completion items.
connection.onCompletion(
async (params: node.TextDocumentPositionParams): Promise<node.CompletionItem[] | node.CompletionList | undefined> => {
console.log("completion");
let doc = documents.get(params.textDocument.uri);
let list:node.CompletionList = node.CompletionList.create([], true);
list.items = list.items.concat(comp.GetAGKKeywordCompletionItems(), comp.GetAGKCommandCompletionItems(), agkDocs.getALLCompletionItems());
list.items.push(sense.GetCommentSnippetCompletionItem(doc, params.position));
list.items.push(sense.GetCommentSnippetCompletionItem(doc, params.position, true));
console.log("END completion");
return list;
}
);

Nuxt.js - Implementing a component using Plugin

I would like to implement a custom Toaster component into my NuxtJs application by this method this.$toast.show({}) What is the best way of approaching this? Sadly I can't find any documentation on this.
Sorry, I arrive one year late...
I had the same proplem. Here is my code:
The index of my plugin (index.js ; Nofification.vue is a classical Vue component):
import Notifications from './Notifications.vue'
const NotificationStore = {
state: [], // here the notifications will be added
settings: {
overlap: false,
horizontalAlign: 'center',
type: 'info',
timeout: 5000,
...
},
setOptions(options) {
this.settings = Object.assign(this.settings, options)
},
removeNotification(timestamp) {
...
},
addNotification(notification) {
...
},
notify(notification) {
...
},
}
const NotificationsPlugin = {
install(Vue, options) {
const app = new Vue({
data: {
notificationStore: NotificationStore,
},
methods: {
notify(notification) {
this.notificationStore.notify(notification)
},
},
})
Vue.prototype.$notify = app.notify
Vue.notify = app.notify
Vue.prototype.$notifications = app.notificationStore
Vue.component('Notifications', Notifications)
if (options) {
NotificationStore.setOptions(options)
}
},
}
export default NotificationsPlugin
Here I call my plugin and inject it in Nuxt:
import Notifications from '~/components/NotificationPlugin'
Vue.use(Notifications)
export default (context, inject) => {
inject('notify', Vue.notify)
}
In my case, I use it in another plugin (nuxtjs axios).
import NOTIFICATIONS from '~/constants/notifications'
export default function ({ error, $axios, app }) {
// Using few axios helpers (https://axios.nuxtjs.org/helpers):
$axios.onError((axiosError) => {
// eslint-disable-next-line no-console
console.log('Axios: An error occured! ', axiosError, axiosError.response)
if (process.server) {
...
} else {
app.$notify({
message: 'Mon message',
timeout: NOTIFICATIONS.DEFAULT_TIMEOUT,
icon: 'tim-icons icon-spaceship',
horizontalAlign: NOTIFICATIONS.DEFAULT_ALIGN_HORIZONTAL,
verticalAlign: NOTIFICATIONS.DEFAULT_ALIGN_VERTICAL,
type: 'success',
})
console.log('PRINT ERROR')
return Promise.resolve(true)
}
})
}
As I injected it, I think I could have done export default function ({ error, $axios, app, $notify }) { and directly use $notify (and not the app.$notify).
If you want a better understanding, feel free to consult #nuxtjs/toast which works the same way:
https://github.com/nuxt-community/community-modules/blob/master/packages/toast/plugin.js
And the matching Vue component:
https://github.com/shakee93/vue-toasted/blob/master/src/index.js
Good luck, this is not easy stuff. I'll try to add something easier to understand in the docs!
you can find in this package https://www.npmjs.com/package/vue-toasted
installation
npm install vue-toasted --save
make a file as name toast.js in plugin folder
toast.js
import Vue from 'vue';
import Toasted from 'vue-toasted';
Vue.use(Toasted)
add this plugin to nuxt.config.js
plugins: [
{ src: '~/plugins/toast', ssr: false },
],
now you able to use in your methods like this
this.$toasted.show('hello i am your toast')
hope this helps

Searching for ObjectID after implementing routing in Algolia

I have feature whereby am constructing a url like :
http://localhost/listings?q=&idx=content_index&p=0&dFR[objectID][0]=97&dFR[objectID][1]=96
It creates a facetFilters: [["objectID:97","objectID:96"]]"}. I have a clear All feature also which clear all the filters:
search.addWidget(
instantsearch.widgets.clearAll({
container: '#clearAll',
templates: {
link: '<i class="icon icon-undo2"></i>'
},
autoHideContainer: false,
clearsQuery: true
})
);
This works perfectly fine and clears the above filter also. But the issue came when started routing. With routing,
http://localhost/listings?q=&idx=content_index&p=0&dFR%5Bgenres.name%5D%5B0%5D=Comedy
changed to :
http://localhost/listings?genres=Comedy
Have done the below changes for the above:
routing: {
stateMapping: {
stateToRoute(uiState) {
return {
query: uiState.query,
// we use the character ~ as it is one that is rarely present in data and renders well in urls
genres:
uiState.refinementList &&
uiState.refinementList['genres.name'] &&
uiState.refinementList['genres.name'].join('~'),
page: uiState.page
};
},
routeToState(routeState) {
return {
query: routeState.query,
refinementList: {
'genres.name': routeState.genres && routeState.genres.split('~'),
},
page: routeState.page
};
}
}
},
Have to implement the same functionality for objectID. How to do that?

Custom proxies on Stores and Models seems inconsistent (and does not work on Models)

Am using Extjs 4, and have created a custom Rest Proxy to handle communication with my Zend backend api.
(See post http://techfrere.blogspot.com/2011/08/linking-extjs4-to-zend-using-rest.html)
When using a Store to handle communication, I was using Ext.require to load the proxy, and then referenced the proxy on the type field and all was good and it loaded my data: as per:
Ext.require('App.utils.ZendRest');
...
proxy : {
type : 'zest', // My custom proxy alias
url : '/admin/user'
...
}
I then decided to try to use the proxy directly on a model... and no luck. The above logic does not work.
Problems
1. When referencing zest, it does not find the previously loaded ZendRest class (aliased to proxy.zest)
2. It tries to load the missing class from App.proxy.zest (which did not exist.)
So I tried moving my class to this location and renaming to what it seemed to want. No luck.
It loads the class, but still does not initialize the app... I get no errors anywhere so v difficult to figure out where the problem is after this...
For now it seems I will have to revert to using my Zend Rest proxy always via the Store.
Question is... has anyone else seen the behavior? Is it a bug, or am I missing something?
Thanks...
Using your proxy definition, I've managed to make it work.
I am not sure why it doesn't work for you. I have only moved ZendRest to Prj.proxy namespace and added requires: ['Prj.proxy.ZendRest'] to the model.
Code:
// controller/Primary.js
Ext.define('Prj.controller.Primary', {
extend: 'Ext.app.Controller',
stores: ['Articles'],
models: ['Article'],
views: ['article.Grid']
});
// model/Article.js
Ext.define('Prj.model.Article', {
extend: 'Ext.data.Model',
fields: [
'title', 'author', {
name: 'pubDate',
type: 'date'
}, 'link', 'description', 'content'
],
requires: ['Prj.proxy.ZendRest'],
proxy: {
type: 'zest',
url: 'feed-proxy.php'
}
});
// store/Articles.js
Ext.define('Prj.store.Articles', {
extend: 'Ext.data.Store',
autoLoad: true,
model: 'Prj.model.Article'
});
// proxy/ZendRest.js
Ext.define('Prj.proxy.ZendRest', {
extend: 'Ext.data.proxy.Ajax',
alias : 'proxy.zest',
appendId: true,
batchActions: false,
buildUrl: function(request) {
var me = this,
operation = request.operation,
records = operation.records || [],
record = records[0],
format = me.format,
reqParams = request.params,
url = me.getUrl(request),
id = record ? record.getId() : operation.id;
if (me.appendId && id) {
if (!url.match(/\/$/)) {
url += '/';
}
url += 'id/' + id;
}
if (format) {
reqParams['format'] = format;
}
/* <for example purpose> */
//request.url = url;
/* </for example purpose> */
return me.callParent(arguments);
}
}, function() {
Ext.apply(this.prototype, {
actionMethods: {
create : 'POST',
read : 'GET',
update : 'PUT',
destroy: 'DELETE'
},
/* <for example purpose> */
reader: {
type: 'xml',
record: 'item'
}
/* </for example purpose> */
});
});
Here is working sample, and here zipped code.