for my blog app in NextJS I’m trying to create a route for usernames. If a user navigates to /@${username}
I want to display the page in /pages//index.tsx
. That works but if I randomly navigate to /abc
it displays that page (with an error, obviously) and not the default 404 page
2
Answers
I’m blind-flying on this right now as I don’t have Next.js and/or Node installed on my current machine, but is it an idea to create a redirect from
/@${username}
to/${username}
?If that could work for you, try adding the following to your
next.config.js
:With this configuration, when a user navigates to
/@[username]
, it will redirect to/user/[username]
, which will be handled by the dynamic route file atpages/user/[username].tsx
.One way to implement the desired behavior is with
getServerSideProps
:Another option would be to use
router
on the client and check therouter.query.username
after hydration.