Search code examples
next.jsdynamic-routing

next.js - dynamic route consisting of multiple slugs?


Is it possible to structure a route that contains dynamic parts in predefined format, such as /[name]-id[id], for example to have routes /bob-id303 or /mary-id205?

What I tried is create a file [name]-id[id].js. Inside getInitialProps I console.log the ctx and it contains

  pathname: '/[name]-id[id]',
  query: { 'name]-id[id': 'bob-id303' },
  asPath: '/bob-id303',

On the other hand, calling the file [[name]]-id[id]].js gives

Failed to reload dynamic routes: Error: Optional route parameters are not yet supported ("[[name]-id[id]]").

I'd like to get the name and id directly, then pass them through initial props to the page. I'm aware I can parse asPath, but is there another way to do this?


Solution

  • You could use /[slug] and then do slug.split("-id"). However you may be better off doing the id alone followed by a fetch for metadata because the name could change and then that url would potentially 404.