machineghost
machineghost

Reputation: 35790

Next.js: How Can I Make Dynamic Routes With Spaces Work?

I have a getStaticPaths function that generates two nearly identical paths: foo%20bar and foo_bar. My foo_bar path works great, but for some reason the foo%20bar path doesn't work: it routes to my 404 page (whether I literally browse to foo%20bar or just foo bar).

Is there some trick to make URIEncoded spaces (ie. %20) work in dynamic Next.js routes?

Upvotes: 2

Views: 2266

Answers (3)

Deepak Mukka
Deepak Mukka

Reputation: 396

When returning parms in getStaticPaths you can use decodeURIComponent to map the path with spaces, the space maps to %20 in browser and renders the route

const dummyPaths = dummyAPIResponse.map((id: string) => {
    return {
        params: {
            id: decodeURIComponent(id.toLowerCase()),
        },
    };
});

Discussion from github: https://github.com/vercel/next.js/issues/54096

Upvotes: 1

Uday
Uday

Reputation: 71

I encountered this same problem but the reason was using --turbo flag in dev scripts in package.json. After researching for a bit I found out that the rust based turbopack bundler causes this problem, So I removed the --turbo flag and by compiling with native next.js webpack compiler the problem got solved.

Upvotes: 1

juliomalves
juliomalves

Reputation: 50278

Sadly, that isn't possible yet as reported here.

You can use encodeURIComponent on the foo%20bar path in your getStaticPaths, but it'll only be accessible as foo%2520bar in the browser, and not foo%20bar as you would expect.

Upvotes: 2

Related Questions