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
Create a Middleware
Create a file named middleware.js
or .tsx
within the src
folder.
Word: if you do not have
src
folder create themiddleware.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";
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"] };
Shield routes inside listing
Lets shield all routes inside dashboard folder.
export { default } from "next-auth/middleware";
export const config = { matcher: ["/dashboard/", "/dashboard/:path*"] };
Learn extra about matcher and NextAuth Middleware
Thats It!
Completely happy Coding!