Next.js Redirects: redirects key in next.config.js vs. redirect object in getServerSideProps() - next.js

Let's just say I want to redirect my index page to the about page in Next.js. It seems like I have 2 options:
1. Adding the redirects key in next.config.js
module.exports = {
async redirects() {
return [
{
source: '/',
destination: '/about',
permanent: true,
},
]
},
}
2. Returning the redirect object inside the getServerSideProps() function
// pages/index.js
export async function getServerSideProps() {
return {
redirect: {
destination: '/about',
permanent: true,
},
};
};
What is the difference between these 2 options?

According to your logic, they're the same in terms of functionality, but redirect on your page pages/index.js will have more flexibility and more customization. For example, you want to redirect to another page conditionally like below
// pages/index.js
export async function getServerSideProps() {
const value = true; //receive data from APIs
//if value is true, redirect to `/help` instead of `/about`
if(value) {
return {
redirect: {
destination: '/help',
permanent: true,
},
};
}
//TODO: You can add your logic here before redirection
return {
redirect: {
destination: '/about',
permanent: true,
},
};
};
You cannot achieve that logic with redirects() under next.config.js. You can imagine that it's like configurations being only applied once without the complicated logic requirement.
You can consider these use cases:
If you don't want to have complicated routing logic and just use them as one-time setups - Use redirects() in next.config.js
If you have some logic to handle routings in pages and it's relied on external resources - Use redirect in pages themselves

Related

Redirect to multiple routes based on JWT Claim using vuejs routes

Currently i have the following route
routes.push({
path: "/",
redirect: "/Dashboard"
});
When I login, it will redirect me to the /dashboard screen.
But how can I update the route so that when I log in I can check the claims and then based on the role, redirect to a different view.
I tried the following, this is just sudo code as I cant really get it to work. Also if I can I would like to add an alias. Even if I can get it to work is would this be the correct way of doing it?
routes.push({
path: "/",
alias: "/dashboard", --> This does not seem to work with redirect.
redirect: to => {
getUserType(msalInstance).then(userType => {
if(userType == 'Client'){
return { path: '/clients/2/detail' }
}
else {
return { path: '/dashboard' }
}
});
}
});
and the route for the client-detail looks as follows.
routes.push({
path: "/clients/:id?/detail",
name: "client-detail",
props: true,
meta: {
requiresAuth: true,
layout: simpleLayout,
allowedUsers: clientUserTypes
},
component: loadView("client-detail"),
});
I have looked the the beforeEnter hook but when I add it, it seems to get ignored because the redirect is there.

How to translate routes in Next.js without prefixing

I need to be able to translate routes without prefixing the url with a locale. I've read the nextJs docs. I've tried next-translate-routes. I am having a hard-time finding the solution to something that should be pretty simple with any web server framework.
mydomain.com/home-insurance [en]
mydomain.com/assurance-habitation [fr]
Then I need to be able to retrieve the locale and pass it to my fetch methods. Things I've tried:
1: Adding rewrites in the next.config.js:
const nextConfig = {
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
async rewrites() {
return {
beforeFiles: [
{
source: '/assurance-habitation',
destination: '/home-insurance'
}
],
}
},
}
But without the prefixx, nextjs has no idea that /assurance-habitation is in french.
2: Using next-translate-routes with routes.json
{
"home-insurance": {
"en": "home-insurance",
"fr": "assurance-habitation"
}
}
Then,
export async function getStaticProps({ locale }) {
...
}
locale here always has a value of en no matter what url is navigated to. Also when I navigate to assurance-habitation it redirects to home-insurance (and yes I've removed the rewrites).

How to configure path in NextJS

I have the following addresses /blog/post-1, /blog/post-2 and I want to rewrite all paths to /post-1, /post-2. I configure in the file next.config.js as follows
async rewrites() {
return [
{
source: '/:slug',
destination: '/blog/:slug',
},
]
}
However, the old path and the new path both work? What should I do?
You have them set up the wrong way around if you are trying to redirect from /blog/post-1 to /post-1/ and you need the path parameter.
From the docs https://nextjs.org/docs/api-reference/next.config.js/rewrites
module.exports = {
async rewrites() {
return [
{
source: '/blog/:path*',
destination: '/:path*', // The :path parameter is used here so will not be automatically passed in the query
},
]
},
}

How to rewrite homepage based on hostname

I'd like to show two different pages at '/' depending on the hostname (the value for req.hostname). This is because I have a subdomain xxx.mydomain.com that needs to show just one page at the root URL. The idea is to have a CNAME for the subdomain that points to the same server as www. I'm using next version 11.1.2 .
My homepage (/pages/index.js) uses getStaticProps to get data for the page with a revalidate interval of 2 seconds. The page on the production branch works great currently without any rewriting.
I tried using the rewrites option in next.config.js and was able to use this to rewrite all other routes, but rewriting with source: '/' did not do anything. If the source was any other page it worked perfectly. This is pretty much what the next.config.js file looked liken when I tried the rewrite:
const withFonts = require('next-fonts');
const withTM = require('next-transpile-modules')(['#cal-frontends/shared']);
require('dotenv').config({ path: '../../.env' });
module.exports = withTM(withFonts({
async rewrites() {
return [
{
source: '/', // this one still showed the homepage at '/'
destination: '/mission',
},
{
source: '/foo', // this one showed the contact page at '/foo'
destination: '/contact',
},
]
},
webpack(config, options) {
return config;
},
}));
I tried many strategies, including this kind of configuration in server.js
server.get('/',function(req,res){
console.log('trying to redirect', )
console.log('req.hostname', req.hostname)
if (req.hostname === 'mission.mydomain.com') {
console.log('this should show mission', )
return app.render(req, res, '/mission', {})
} else {
handle(req, res);
}
});
This unfortunately did not seem to override the static caching that happens with getStaticProps – you will only see the correct page for the hostname if you load and then reload after it revalidates.
Is there an elegant way to do this?

Next.js redirect www to non www

I have been trying to find a workable solution this searching google but can't find anything solid. I am hosting my Next.js application on Vercel.
When I run a seo check it moans about me having the site available on www and non www and says I should pick one and get it to redirect so in my case, if someone types in www.example.com I would prefer it left of the www.
Since I don't have a htaccess file I can do this in, how would I do it?
Not sure if it matters, but I am using WordPress as my backend aka: Headless Wordpress
You should be able to use host-based redirects now since Next v10.2. See https://nextjs.org/docs/api-reference/next.config.js/redirects#header-cookie-and-query-matching.
In next.config.js:
module.exports = {
// ...
redirects: async () => [
{
source: '/:path*',
has: [{ type: 'host', value: 'www.yourdomain.com' }],
destination: 'https://yourdomain.com/:path*',
permanent: true
}
]
}
you can easily handle permanent redirection in nextjs using the below-mentioned code.
export const getServerSideProps = async (context) => {
const { req, res } = context;
if (req.headers.host.match(/^www/) !== null) {
res.writeHead(301, {
location: "https://" + req.headers.host.replace(/^www./, "") + req.url,
});
res.end();
}
return { props: {} };
};

Resources