Next.js 13 jwt authentication protected routes httpOnly cookie with App Directory
3 min read
6 months ago
Published on Apr 23, 2024
This response is partially generated with the help of AI. It may contain inaccuracies.
Table of Contents
Step-by-Step Tutorial to Implement JWT Authentication and Protected Routes with Next.js
-
Create a Next.js Project:
- Start by creating an empty Next.js project.
- Install necessary dependencies like
cookie
,jsonwebtoken
, andaxios
for handling authentication.
-
Set Up Client-Side Authentication:
- Import
useClient
at the top of your file to indicate that the authentication will be handled on the client-side.
- Import
-
Create an API for User Authentication:
- Create an API route named
route.ts
under thepages
directory to handle user authentication. - Implement logic to check user credentials (e.g., username and password) and return a JWT token in response.
- Create an API route named
-
Handle Environment Variables:
- Define environment variables like
JWT_SECRET
andNODE_ENV
to store sensitive information securely.
- Define environment variables like
-
Generate JWT Token:
- Use the
jsonwebtoken
library to sign a JWT token with the user's username, secret, and expiration time (e.g., 30 days). - Serialize the token and store it in an HTTP-only cookie for secure storage.
- Use the
-
Authenticate User on the Client-Side:
- Make an API request to the authentication endpoint using
axios
orfetch
to authenticate the user. - Ensure that the user provides correct credentials (e.g., username: admin, password: admin) to receive a valid JWT token.
- Make an API request to the authentication endpoint using
-
Redirect Authenticated Users:
- Import the
Router
module to handle client-side navigation. - Redirect authenticated users to a protected dashboard page upon successful authentication.
- Import the
-
Protect Routes with Authentication:
- Create a layout component (e.g.,
layout.tsx
) to protect routes under the dashboard by checking the JWT token stored in the cookie. - Use
cookie-store
to access and manage cookies conveniently.
- Create a layout component (e.g.,
-
Verify JWT Token:
- Implement logic to validate the JWT token on the client-side by retrieving it from the cookie store.
- Ensure that the token is valid and not expired to authenticate the user.
-
Handle User Logout:
- To log out the user, expire the JWT token instantly by setting the cookie's
max-age
to -1. - Implement a logout route to clear the JWT token and redirect the user to the login page.
- To log out the user, expire the JWT token instantly by setting the cookie's
-
Finalize and Test:
- Test the entire authentication flow by logging in, accessing protected routes, and logging out.
- Ensure that the authentication mechanism works as expected and provides a secure user experience.
By following these steps, you can successfully implement JWT authentication and protected routes in your Next.js application, ensuring secure user authentication and authorization.