user171453
user171453

Reputation:

Adding prefix to Nextjs dynamic route

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.

Upvotes: 3

Views: 7206

Answers (3)

xuxu
xuxu

Reputation: 6492

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*',
      },
    ]
  },
}

Upvotes: 2

Fernando Rojo
Fernando Rojo

Reputation: 3258

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>
}

Upvotes: 13

rovaniemi
rovaniemi

Reputation: 97

Next.js does not support this yet.

You should watch this issue.

Upvotes: -2

Related Questions