Home > Mobile >  Next js dynamic pathname routing
Next js dynamic pathname routing

Time:06-22

For example, there is a pathname that comes to me as /example/123 and I need to redirect it to /otherExample/123.

I am using next/router. and I am getting urli coming as router.asPath.

if(router.asPath == '/example/123') {
   Router.push('/otherExample/123')
}

I don't know how to do it because 123 part is dynamic.

CodePudding user response:

You can solve this by using next's redirect functionality. You can read more about it here.

In next.config.js add the redirects key:

async redirects() {
    return [
      {
        source: '/example/:slug',
        destination: '/otherExample/:slug',
        permanent: true,
      },
    ]
  },

If you want the redirect to be cached forever, set permanent to true. Otherwise, you should set it to false.

CodePudding user response:

Just cut the last part of the path and use it down :

const pathParts = path.split('/');
const exampleId = pathParts[pathParts.length - 1];
Router.push(`/otherExample/${exampleId}`);

Or easire just use router.query to get the value of the parameter :

const { exampleId } = router.query;
if (exampleId) {
  Router.push(`/otherExample/${exampleId}`);
}
  • Related