,

Protected Routes with Next.js JWT Authentication and HttpOnly Cookies in App Directory

Posted by






Next.js JWT Authentication with Protected Routes

Next.js JWT Authentication with Protected Routes

Next.js is a popular framework for building React applications. It provides great support for server-side rendering, static site generation, and API routes. In this article, we will learn how to implement JWT authentication and protect routes in a Next.js app.

Setting up JWT Authentication

First, we need to install the necessary packages for JWT authentication. We can use the `jsonwebtoken` package to generate and verify JWT tokens. Additionally, we can use the `cookie` package to handle HTTP-only cookies for secure storage of the JWT token.

    
      npm install jsonwebtoken cookie
    
  

Next, we need to create a utility function to generate JWT tokens and set them in HTTP-only cookies. We can create a function called `setAuthCookies` that takes a user object and returns a signed JWT token and an HTTP-only cookie.

    
      const jwt = require('jsonwebtoken');
      const cookie = require('cookie');

      function setAuthCookies(user) {
        const token = jwt.sign({ id: user.id, email: user.email }, process.env.JWT_SECRET);
        const cookieHeader = cookie.serialize('token', token, {
          httpOnly: true,
          secure: process.env.NODE_ENV === 'production',
          sameSite: 'strict',
          path: '/'
        });
        return cookieHeader;
      }
    
  

Protecting Routes

Now that we have set up JWT authentication, we can protect certain routes in our Next.js app. We can create a Higher Order Component (HOC) called `withAuth` that checks for the presence of a valid JWT token in the cookie and redirects the user if they are not authenticated.

    
      import { useRouter } from 'next/router';

      function withAuth(Component) {
        return function(props) {
          const router = useRouter();
          // logic to check for JWT token in cookie
          if (!hasToken) {
            router.push('/login');
            return null;
          }
          return ;
        }
      }
    
  

Conclusion

In this article, we learned how to implement JWT authentication and protect routes in a Next.js app. By using JWT tokens and HTTP-only cookies, we can ensure a secure and reliable authentication system for our application.


0 0 votes
Article Rating
20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Anas Al-aqeel
1 year ago

now we can't use "use client" in layout.tsx I think its time to think about middleware or somthing

pega esse feedback
1 year ago

Jesus Christ man. You are amazing <3 Please keep making videos. The dev world needs you.

MythicNanda
1 year ago

Awesome!

Suha Karkhy
1 year ago

i love you

Naxi Ryu
1 year ago

Please implement refresh token

Miguel Cardenas
1 year ago

Great tutorial thank you!
I just have one question, how would you send the cookies from server side components?
What occurred tp me is each time I make the request from the server, I get the cookie manually and add it to the 'Cookie' header on each request, is there a better way to do it? ( I saved the cookie using cookies().set(…) from 'next/headers' after my login request)
I would appreciate your input, thank you 🙂

Mohammed Mshal
1 year ago

You're amazing, bro❤️

Jože Kuhar
1 year ago

Great video, one question, is there a way that I can fetch data with cookie in server component and than update cookie on server side if it is wrong. I tried lot of things but it is imposible to set new cookie (with new access and refresh token) from server side component.

Ali Moayedi
1 year ago

👍👍

Dolores La Flipo Flopo
1 year ago

making layout.tsx a client component is not recommended by NextJS. and now with server actions most of it is outdated

Kamzata
1 year ago

I have a question: `verify` should return the username, right? So, I can response with that in /api/auth/me and get it back in the getUser() function in layout.tsx. But how can I pass the username to the page.tsx? Could I call the the endpoint /api/auth/me again from page.tsx since it will be deduplicated using fetch? Or what should I do in order to get the username in page.tsx?

Jacob MacFarlane
1 year ago

so inside of api/auth/login/route.ts where you had the if statement checking to make sure it was admin admin, that is where you would make a POST request to the database you are using? and then pass through the body to it as the values?

Jacob MacFarlane
1 year ago

Im having a hard time trying to figure out how you would do this if the API you are trying to hit requires an API_KEY. From my experiences whenever i tried to do a fetch the fetch would fail becasue the key would be read as undefined within the client component?

Ken Verdadero
1 year ago

Exaclty what I needed to learn, all in one video. Thank you!

OldNoob
1 year ago

hi excellent tutorials, if i have y own backend that return response jwt token, i dont have setting up the routes in api login auth right?

Mohammed Mehdi
1 year ago

is there no way to do this apart from making my layout.tsx a client component. Because i want my layout.tsx to be a server component so that i can set the metadata object on that route.

Niloy Kumar
1 year ago

Thanks man Love from Bangladesh

Prashant
1 year ago

Thank you

Vitor D. Cardoso
1 year ago

great video, thanks

Radheya Mansel
1 year ago

Excellent, worked first time … thank you, I've been pulling my hair out all day