Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i get params in nexjs middleware?

I have a middleware that triggers on every request. How do I get the id in the url?
if it were like this

http://localhost:3000/dash/profile/103848028402840
http://localhost:3000/dash/home/103848028402840;
http://localhost:3000/dash/notification/103848028402840

I can’t split profile/ because the next time the middleware runs, it wouldn’t be profile, but home.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and [middleware].js will not work either right?

>Solution :

The best solution is to use Next Catch all route feature

you need to change your filename to [...middleware].js as Rest Parameters will help you get access to the data in url.

then in page you can do like

import { useRouter } from "next/router";

export default function CustomPage() {
    const router= useRouter()
    console.log(router.query)
    const {params = []} = router.query
   // you will get all the data in params array and last index will be id
    console.log(params[2])  
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading