0

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 don't necessarily need to have them in the config file. The `redirects` property in `next.config.js` is an async function, you could move the logic to generate the redirects to a helper and just call the function in the config. – juliomalves Jan 28 '22 at 20:19
  • @juliomalves could you be a bit more specific on how to call that function from within next.config.js? I've tried importing the helper function as well as requiring it as a const and neither are working – JordyJordyJordyJordan Jan 29 '22 at 19:37
  • @juliomalves Hey so I tried adding this to my nextjs.config: `import { redirects } from '@lib/helpers'` and got the following error: `SyntaxError: Cannot use import statement outside a module` – JordyJordyJordyJordan Feb 18 '22 at 16:08
  • Use `require` instead, i.e. `const redirects = require('@lib/helpers').redirects`. Or convert your config file to ESM so you can use `import`, see https://stackoverflow.com/a/69781269/1870780. – juliomalves Feb 18 '22 at 16:37

2 Answers2

1

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");
Kosti
  • 106
  • 1
  • 4
1

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
 }