Krishna Rathore
Krishna Rathore

Reputation: 1

How to protect API routes in next js with next auth

I want to secure my API routes in next js I tried the getServerSession method it works but only on client side I want to use both side please I need solution. I have a admin API and I want to make only for admin and for both side for client and server. Also on next-auth I tried the credentials provider but it's not providing the access token.

Secure API routes in next js

this is i am using now in middleware - ` const AdminAccessAPI = req.nextauth.token?.role !== "ADMIN" && req.nextUrl.pathname.startsWith("/api/admin") && req.nextauth.token?.isVerified !== true

if(AdminAccessAPI){
    return NextResponse.json("Unauthorized", { status: 401 });
}

` but this is not working on server side and server components

Upvotes: 0

Views: 657

Answers (1)

Hashir Nouman Qazi
Hashir Nouman Qazi

Reputation: 1

You can protect routes in next.js by adding middleware.ts (or .js based on the language you choose to code) and add the following code.

middleware.ts
    export { default } from "next-auth/middleware";

    export const config = {
        // specify the route you want to protect
        matcher: ["/dashboard"],
    };

Upvotes: -1

Related Questions