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.

Cookie-based authentication

Cookie-based authentication

We can authenticate users by JWT token which is stored in our application. So there are three ways to store the token. Local storage, session storage and cookies. Out of these three, cookie is a safe and convenient option to store the JWT token than others. And it offers HTTP only flags like HTTP only, secure, same site, etc. for better protection. Not only that, we can handle cookies from server side as well. So in our project, we will implement cookie based authentication that is we will store the JWT token in the cookie and retrieve the cookie for authentication. I will use the cookies from the next headers. So inside the lib directory, I will create a file called cookies.js and will create a function to set the cookie by saying export function setCookie. It will receive name and value and options with default value empty object. Now to create or generate the cookie, we will use the cookies.set method. The set method will take three parameters, cookie name, value, and the options…

Contents