Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect api routes with middleware in nextJS?

I'm new to next.js and I wanted to know if I could protect a whole API route via middleware. So for example if i wanted to protect /api/users Could I create /api/users/_middleware.ts and handle authentication in the middleware and not have to worry about authentication in the actual api endpoints? If so, how would I go about doing that? The library i'm using right now is @auth0\nextjs-auth0 so I guess it would look something like this? (Also please forgive me if I code this wrong, I am doing this in the stackoverflow editor)

export default authMiddleware(req,res)=>{
const {user,error,isLoading} = whateverTheNameOfTheAuth0HookIs()
if(user)
{
// Allow the request to the api route
}
else
{
// Deny the request with HTTP 401
}
}

Do I have the general idea correct?

like image 986
Brandon Piña Avatar asked Dec 28 '25 19:12

Brandon Piña


1 Answers

next-auth v4 introduced middleware for this purpose. The basic use case is pretty simple. You can add a middleware.js file with the following:

export { default } from "next-auth/middleware"
export const config = { matcher: ["/dashboard"] }

Other use cases can be found in the documentation

like image 79
magicDev Avatar answered Dec 30 '25 23:12

magicDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!