I have a component that links to a NextJS page in which I'm using getServerSideProps and need to access the params and the query string.
I really would like to have a 'clean' url such as 'domain.com/usersname/likes' without the '?userId=h337dhdh37dhdhd' on the end. Is it possible like this?
<Link href={`/${user?.username}/likes?userId=${id}`} as={`/${user?.username}/likes`}>
...
</Link>
In my getServerSideProps I'm using context as per the Next documentation:
export async function getServerSideProps(context) {
const username = context.params.username;
const userId = context.query.userId;
...
}
The params (username) are fine, but whatever I do the userId is always undefined. Can anyone see what I'm doing wrong, please?
EDIT: codesandbox link: https://codesandbox.io/s/nifty-bush-livm7 - based on Restricted Beam's answer below
Any help very much appreciated, Matt
If your goal is to have a clean URL without the '?query=something' , you should try the slug and dynamic routes feature of nextjs. For using this feature:
So for "domain/usersname/likes/userId", your [...slug].js file will be in the root directory and to access its value you will use context like the following:
export async function getServerSideProps(context) {
const username = context.params.slug[0];
const userId = context.params.slug[2];
...
}
So, if your user visits the link: domain/user-XYZ/likes/12345abc, the slug array would be like:
context.params.slug:["user-XYZ","likes","12345abc"]
Docs: https://nextjs.org/docs/routing/dynamic-routes#catch-all-routes
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments