How would I create a dynamic route in Next.js with the @ symbol?
For example localhost:3000/@some_username
I know you can create dynamic routes within the pages folder but how would I do it with just the @ symbol and no / afterward like the above example.
CodePudding user response:
You can add a prefix by defining a rewrite in your next.config.js.
module.exports = {
async rewrites() {
return [
{
source: '/@:username',
destination: '/users/:username'
}
]
}
}
This redirects all /@{username} routes to /users/{username}.
Some more information about rewrites in nextjs can be found here
CodePudding user response:
It's the same as the standard dynamic routing in Next.js. You don't need rewrites.
Name the file or folder [@:username]
in your root directory.
There are a few ways to do this:
App directory
/app/[@:username]/page.js
Pages directory as file
/pages/[@:username].js
Pages directory as folder
/pages/[@:username]/index.js
The param can be access the query param on the page like
import { useRouter } from "next/router";
const { query } = useRouter();
const username = query["@:username"];