From the course: Master Next.js by Building Scalable Apps with Routing, Databases, and Performance

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Handling private and public routes using middleware

Handling private and public routes using middleware

Ideally, in an application, the admin section should not be accessed by an unauthorized user under any circumstances. But in the current application, we are able to access all the routes by simply changing the URL. So, to check if the user request is authenticated or not. In other words, to check if the user is logged in or not, we will create a middleware that will handle the private and public routes based on the token stored in the cookie. So let me create a middleware.js file inside the src directory and inside it, I will write export default async function handler and will receive request comma response. Now I will get the token by saying const token is equal to req dot get JWT token dot value and also I will create an array for public routes by saying const public routes is equal to in the square brackets adding slash login. Now I will verify the token by writing const isValidToken is equal to await verifyJWT token. If the token is invalid and the user is trying to access routes…

Contents