I am trying to add @ in front of a slug URL. For example: https://example.com/@username.
I tried @[username].js but that is not working.
Is this even possible?
Try using rewrites and some regex. Next.js uses path-to-regexp under the hood.
async rewrites() {
return [
{
source: '/:userId(@[a-zA-Z0-9]+)/:id*',
destination: "/user/:userId/:id*",
}
]
}
On client side use next/link:
<Link href={`@${userId}`}>
<a>user</a>
</Link>
In your backend when you handle users, put the @ in the users' usernames. Then, simply treat the usernames as if they were plain text slugs. This works because @ is allowed in URLs, just like a, b or c.
Working example on StackBlitz.
pages/index.js:
import Link from 'next/link'
const username = '@foobar' // hardcoded example username, this will be recieved from your backend
export default function Index() {
return (
<Link href={username}>
<a>{username}</a>
</Link>
)
}
pages/[username].js:
import { useRouter } from 'next/router'
export default function Username() {
const router = useRouter()
const { username } = router.query
return <h1>User: {username}</h1>
}