i'm having trouble trying to get url params with nextJs. so similar to i'd usually do with express i'd like to get a :param from the url like so
users/:userid/
console.log(req.params.userid)
all i could do is get the "userid" from url like so ?userid= i'm also using typescript
CodePudding user response:
I assume that you want to get the "userid" path variable from the respective page.
If the path users/[userid].tsx
is a page, then it would look like this:
/pages/users/[userid].tsx:
import { useRouter } from 'next/router'
import { NextPage } from 'next'
const UserPage: NextPage = () => {
const router = useRouter()
const { userid } = router.query
// TODO
return <></>
}
export default UserPage
However, if you want to use the route as an API route, then it looks like this:
/pages/users/[userid].ts:
import type { NextApiRequest, NextApiResponse } from 'next'
export default (req: NextApiRequest, res: NextApiResponse) => {
const { userid } = req.query
// TODO
res.status(200).json({ name: `User ID: ${userid}` })
}
CodePudding user response:
It depends on the place that you need this parameters.
For Client side , you have to use useRouter
hook.
For getStaticProps and getServerSideProps you have to use context
object that is passed to this functions automatically.
For Api Routes , it's exactlly like express js
and you can use req.params.userid