Adding prefix to Nextjs dynamic route

Viewed 1714

I have quite a lot of routes defined and one of the routes is dedicated to user profiles.

Each user has a public profile accessible from HTTP://example.com/@username.

I have tried creating file pages/@[username].js but it doesn't seem to work.

Is there a way to have this behavior without passing @ sign with the username because this would greatly complicate index.js handling homepage and I would like to have that code separated.

2 Answers

You can now do this like so in next.config.js

module.exports = {
  async rewrites() {
    return [
      {
        source: '/@:username',
        destination: '/users/:username'
      }
    ]
  }
}

This will make any link to /@username go to the /users/[username] file, even though the address bar will show /@username.

Then, in your /pages/[username].tsx file:

import { useRouter } from 'next/router'

export default function UserPage() {
  const { query = {} } = useRouter()

  return <div>User name is {query.username || 'missing'}</div>
}

Next.js does not support this yet.

You should watch this issue.

Related