DEV Community

Cover image for Handle protected page routes in NextJS using NextAuth
Hidayt Rahman
Hidayt Rahman

Posted on

Handle protected page routes in NextJS using NextAuth

For this article, we will use the middleware technique.

To use this functionality, you must have at least NextAuth.js 4.2.0 and Next.js 12 installed.

Configuration

Let's configure the server by adding a new environment variable to the .env.local file.

NEXTAUTH_SECRET=addAnythingYouLike
Enter fullscreen mode Exit fullscreen mode

Create a Middleware

Create a file named middleware.js or .tsx in the src folder.

Note: if you don't have src folder create the middleware.js on the root folder

Lets add code for middleware

Protect all routes
Use the piece of code below to make all pages protected.

export { default } from "next-auth/middleware";
Enter fullscreen mode Exit fullscreen mode

Protect selective routes
Lets protect profile and posts route with the help of matcher. You can put the route based on your requirements

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

export const config = { matcher: ["/profile", "/posts"] };

Enter fullscreen mode Exit fullscreen mode

Protect routes inside directory
Lets protect all routes inside dashboard folder.

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

export const config = { matcher: ["/dashboard/", "/dashboard/:path*"] };

Enter fullscreen mode Exit fullscreen mode

Read more about matcher and NextAuth Middleware

Thats It!

Happy Coding!

Top comments (1)

Collapse
 
abdurahman_ghazi profile image
abdurahman-ghazi

thanks, Protect routes inside directory saved my time