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

  1. Create a Next.js Project:

    • Start by creating an empty Next.js project.
    • Install necessary dependencies like cookie, jsonwebtoken, and axios for handling authentication.
  2. 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.
  3. Create an API for User Authentication:

    • Create an API route named route.ts under the pages directory to handle user authentication.
    • Implement logic to check user credentials (e.g., username and password) and return a JWT token in response.
  4. Handle Environment Variables:

    • Define environment variables like JWT_SECRET and NODE_ENV to store sensitive information securely.
  5. 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.
  6. Authenticate User on the Client-Side:

    • Make an API request to the authentication endpoint using axios or fetch to authenticate the user.
    • Ensure that the user provides correct credentials (e.g., username: admin, password: admin) to receive a valid JWT token.
  7. Redirect Authenticated Users:

    • Import the Router module to handle client-side navigation.
    • Redirect authenticated users to a protected dashboard page upon successful authentication.
  8. 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.
  9. 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.
  10. 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.
  11. 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.