Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding prefix to Nextjs dynamic route

Tags:

next.js

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.


1 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>
}
like image 130
Fernando Rojo Avatar answered Apr 19 '26 17:04

Fernando Rojo