How to rewrite homepage based on hostname - next.js

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?

Related

NextJS rewrite automatically converting '//' to '/' in url

I have the following entry in my next.config.js file, which points a local path to an external api path.
module.exports = {
async rewrites() {
return [
{
source: '/api_dev/:path*',
destination: 'http:/some_api_path:9080/v1/:path*',
},
]
},
}
when I pass the url '/api_dev/param1/test/param2//param3/test' in my app, nextjs appears to convert the url to '/api_dev/param1/test/param2/param3/test'. How do I prevent this from happening? i.e., I want to keep the double forward slash in the url. Is there a way to do this?

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

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

NextJS config: Move redirects to it's own file

I'm moving from a wordpress site to a new, shiny nextjs site. However, I have hundreds of redirects and I don't want to put them all in the nextjs config file. I like things clean and tidy. I searched around for awhile and didn't find any results on how to do this. Any suggestions?
You need to import it via require, tho remember that u also need to export it as module, so ex.:
const redirectsArray = [
{ source: "/about", destination: "/", permanent: true },
];
async function redirects() {
return redirectsArray;
}
module.exports = {
redirects,
};
and then
const { redirects } = require("./redirects.js");
I got it working while module exporting it as an array instead of an object in the redirects.js
module.exports = redirects
And then add it to the next.config.js like so
async redirects() {
return redirects
}

Exposing Storybook via NextJS route

I have a NextJS app and am using Storybook to develop my components.
After looking through all the NextJS routing documentation, I can't find a way to route to my storybook from within NextJS. Only access pages within the /pages directory.
What I would like to do it to have my StoryBook available at /styleguide from within my Next app thought all environments.
Is someone able to help?
Short answer: No, you can not do that.
But you can always redirect the url /styleguide to another domain where Storybook is running, for example styleguide.example.com. Here, an example based on the official documentation:
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/styleguide',
destination: 'https://styleguide.example.com',
permanent: true,
},
]
},
}
If your URL's would have any parameters for it's origin that you would want to append to the redirects destination, NextJS provides a feature to do just that.
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/styleguide/:pageId/:slug',
destination: 'https://styleguide.example.com/:pageId/:slug',
permanent: true,
},
]
},
}

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