简体   繁体   中英

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?

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

You can use middleware for that, something similar to this example from the documentation.

For a sub-directory inside pages , you can create a _middleware.ts file. It will run for all pages in this directory. It looks something like this:

import { NextRequest, NextResponse } from 'next/server'

export function middleware(req: NextRequest) {
  const basicAuth = req.headers.get('authorization')

  if (basicAuth) {
    // do whatever checks you need here
    const hasAccess = ...

    if (hasAccess) {
      // will render the specified page
      return NextResponse.next()
    }
  }

  // will not allow access
  return new Response('No access', {
    status: 401,
    headers: {
      'WWW-Authenticate': 'Basic realm="Secure Area"',
    },
  })
}

You can find more info in the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM