3

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.

3 Answers 3

13

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>
}
Sign up to request clarification or add additional context in comments.

4 Comments

okay tested working. ```const router = useRouter(); const { username } = router.query;````
I added an example with useRouter to my answer.
Btw the slug is passed a props automatically no need to call userRouter export default function Page({ params }) { console.log (params.username) }
You aren't always accessing params from the root page though.
2

I am using Next.js 14 with App Router. This works both for /@username and nested paths like /@username/about:

const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/@:username/:path*',
        destination: '/users/:username/:path*',
      },
    ]
  },
}

Comments

-2

Next.js does not support this yet.

You should watch this issue.

1 Comment

It does support it now, see my answer: stackoverflow.com/a/67929729/7869175

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.