Next.js Discord

Discord Forum

next-auth with next-js

Unanswered
Iridescent shark posted this in #help-forum
Open in Discord
Iridescent sharkOP
Is it possible to customize next-auth middleware, so that it returns status code 401 - unauthorized as response instead of navigating to /sign-in page?

3 Replies

technically you can access HTTP request headers from middleware, and a JWT token are one of cookies(http header), so you can access the jwt.
getToken() would work( im not sure) to grab the jwt, then return http response from middleware.
@tafutada777 technically you can access HTTP request headers from middleware, and a JWT token are one of cookies(http header), so you can access the jwt. getToken() would work( im not sure) to grab the jwt, then return http response from middleware.
Iridescent sharkOP
Something like this?
export default async function middleware(req: NextRequest, res: NextResponse, event: NextFetchEvent) {

  //If request to api handle with custom middleware
  if (req.nextUrl.pathname.startsWith('/api')) {
    const token = await getToken({ req, secret });

    const found = securedApiPaths.pathes.find((path) => req.nextUrl.pathname.includes(path.route));
    //If path and method is found and token not provided then return not authorized
    if (found && found.methods.includes(req.method as MethodType) && !token) {
      return NextResponse.json({ message: "Token not provided" }, { status: 401 });
    }

    //Check that user is in admin role

    return NextResponse.next();
  }

  //Else handle pages with normal next-auth middleware
  const withAuthResult = withAuth(function (request: NextRequestWithAuth) {
    //Check that user is in admin role

  })
  return withAuthResult(req as NextRequestWithAuth, event);
}

const securedApiPaths: SecuredApiPathes = {
  pathes: [
    {
      route: '/api/posts',
      methods: ["POST", "PUT", "DELETE"]
    }
  ]
}

export const config = {
  matcher: [
    '/api/:path*',
    '/posts/create',
    '/posts/update/:path*'
  ]
}
yup