This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Handle protected page routes in NextJS using NextAuth


For this text, we are going to use the middleware method.

To make use of this performance, you need to have no less than NextAuth.js 4.2.0 and Subsequent.js 12 put in.



Configuration

Let’s configure the server by including a brand new surroundings variable to the .env.native file.

NEXTAUTH_SECRET=addAnythingYouLike
Enter fullscreen mode

Exit fullscreen mode



Create a Middleware

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

Word: if you do not have src folder create the middleware.js on the basis folder

Lets add code for middleware

Shield all routes
Use the piece of code beneath to make all pages protected.

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

Exit fullscreen mode

Shield selective routes
Lets shield profile and posts route with the assistance of matcher. You’ll be able to put the route based mostly in your necessities

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

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

Enter fullscreen mode

Exit fullscreen mode

Shield routes inside listing
Lets shield all routes inside dashboard folder.

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

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

Enter fullscreen mode

Exit fullscreen mode

Learn extra about matcher and NextAuth Middleware

Thats It!

Completely happy Coding!

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?