javascriptreactjsbuildnext.jsconfig

Next.js Redirects in next.config.js dynamicly


I want to update Redirects routes after build of project. So, we have a redirect routes on BE Api.

I want to get it and implement to next.config.js dynamicly, here what i tried to do.

const getUrls = () =>
    new Promise(resolve => {
        setTimeout(() => resolve(fetch("https://api.mocki.io/v1/a0b7f0b0").then(function(response) {
            return response.json();
          }).then(function(data) {
            return data.data;
          }) ), 3000);
    });

    // ExampleResponse = {
    //     "data":[
    //         {
    //             "source":"/test",
    //             "permanent":true,
    //             "destination":"/internet-application"
    //         }
    //     ]
    // }
    
module.exports = {
    poweredByHeader: false,
    async redirects() {
        return getUrls();
      },
}

Is there any solution to do it like that. I just want to update redirects from database.If the database update can we trigger redirects without stop project


Solution

  • You can dynamically generate the redirect paths at build time, the problem in your code is that you need to await for the getUrls promise to resolve.

    module.exports = {
        poweredByHeader: false,
        async redirects() {
            return await getUrls();
        }
    }
    

    You can also simplify getUrls to not use setTimeout at all.

    However, if you want to update the redirects at runtime you'll have to setup your own custom server for that.