,

Part 2 – Frontend: Implementing JWT Authentication with Next.js and Django

Posted by






Next.js and Django JWT Authentication | Part 2 – Frontend

Next.js and Django JWT Authentication | Part 2 – Frontend

In part 1 of this series, we looked at setting up Django for JWT authentication. In this article, we will focus on the frontend implementation using Next.js.

Setting Up Next.js

First, make sure you have Node.js installed on your machine. You can then create a new Next.js application using the following command:

npx create-next-app@latest my-next-app

Once the application is created, navigate to the project directory and install the necessary packages:

cd my-next-app
npm install axios js-cookie

Implementing JWT Authentication

Next, we need to implement the JWT authentication in our Next.js application. We will use the axios library for making HTTP requests and the js-cookie library for managing cookies.

Create a new file called api.js in the pages/api directory. This file will contain the functions for handling the authentication requests. Here’s an example of how you can implement the login function:

import axios from 'axios';
import cookies from 'js-cookie';

export const login = async (username, password) => {
  try {
    const response = await axios.post('http://localhost:8000/api/token/', {
      username,
      password
    });
    cookies.set('access_token', response.data.access, {expires: 1});
    cookies.set('refresh_token', response.data.refresh, {expires: 7});
  } catch (error) {
    console.error('Error logging in', error);
  }
};

Protecting Routes

To protect certain routes in your Next.js application, you can create a higher-order component that checks if the user is authenticated. Here’s an example of how you can implement this:

import React from 'react';
import cookies from 'js-cookie';

export const withAuth = (WrappedComponent) => {
  const hocComponent = ({ ...props }) => {
    const accessToken = cookies.get('access_token');
    if (!accessToken) {
      // Redirect to login page
      return 

Please log in to access this page

; } return ; }; return hocComponent; };

Conclusion

With the frontend authentication set up, you can now create a seamless user experience in your Next.js application. By using JWT authentication, you can ensure that your users’ data is secure and protected. In the next part of this series, we will look at how to integrate the backend and frontend for a complete authentication flow.


0 0 votes
Article Rating
30 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Barış Bulut Demir
1 year ago

Hello Bryan. When i use safari, verify is okey not have problem. But when i use chrome or something. it's not working. Bad request. How can i fix it ?

Joy Gaming
1 year ago

When social account login it overwrites normally registered account's first_name, last_name. How can I fix this?

Minseven
1 year ago

would be awesome to have this on Nuxt 3 in the frontend 😀

Paulo Rone
1 year ago

Amazing job!

evren bingol
1 year ago

would you prefer this over your express layer abstraction for jwt

Gabriel Rojas
1 year ago

Does it make sense tu use redux when the caching layer could be provided by nextjs?

Sebastian Castillo
1 year ago

Your programming skills are fantastic, a true fullstack! 👏👏👏
Thank you very much for sharing your knowledge, this tutorial has helped me a lot, I just needed this.
I hope you continue like this! thank you! 🙏

Rocky
1 year ago

Hi. Is it better to move the backend logic in api directory with route.ts structure? as per nextjs documentation

Praneeth G
1 year ago

Access to fetch at 'http://localhost:7000/api/jwt/create/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
I can't get rid of this error. Please help me

Kakashi zet
1 year ago

guys please help after the user enter credentials for some reason django is throwing badreq 400 i saw on the preview "{"non_field_errors":["State could not be found in server-side session data."]}" this only happens when i use nextjs from postman it works just fine, please any one help.

Ryan The Developer
1 year ago

So the verify endpoint isnt reading the cookie or the cookie for the verify has some issue for me – anyione else experiencing this? I login and it says success but then the verify endpoint gets hit and i get redirected to the login

LegacyBuilds
1 year ago

Amazing video man!!!

Derelicts
1 year ago

This was probably the best and most eloquent tutorial I've seen about a topic in web development – thank you Bryan, this content is top tier quality!

micpax1
1 year ago

incredibly useful content. thank you very much Bryan. I am studying the whole series but somehow the Dashboard does not load after login. I don't see the cookies being set and the /api/jwt/verify/ fails with 400 (Bad Request) since there is no token. Did anyone encounter the same issue? Everything seems to work except that the response with the cookies seem ignored by the browser..

mankaa che
1 year ago

Thanks for the great tutorial. I keep having this error that says " useRegisterMutation is not a function or its r

is not iterable" the error comes when i import it in my register component like this "const [register, { isLoading }] = useRegisterMutation();". some one please help on me how to solve this error.

Usman Wahab
1 year ago

Hi! Bryan. There is problem, I have removed access and refresh token from response body in the return statement of custom views. Only using cookies. It works fine for the whole App I have developed a complete Blogging web, the only problem is I am facing is I have to learn django channels, and I want to automatically be authenticated as in other views I am automatically authenticated if in the cookies headers their is token present, this same thing doesn't work for django channels, I search much more than possible 😂, but nothing worked for me. Please if there is some short next totorial you can make is this playlist was only for Authentication, I have moved the app to next level. But the authentication stucked in the middle, because of not working with django channel, if you just can make a short simple text messages with admin side user side, both are authenticated through backend and their names coming in the chat from backend. That's all.

Joao Arthur Bandeira
1 year ago

Hey, great video! I saw that you've changed so the access and refresh token have both the same 1 day life time. But is there a way so i can still make them have different lifetimes? Like 5 min access token and 1 day refresh token. Also, is it possible to deploy both back and front together? Thanks!

Razilator [ProgHub]
1 year ago

Hello, I had a problem when adding RequiredAuth to the layout, the isLoading condition for some reason works all the time, even during authorization. If you remove isloading altogether, then everything works. What could be the reason? I write the code in JS, I looked it all 3 times, I do everything correctly.

Samuel Navarro
1 year ago

why does verify in authApiSlice does not take any arguments? even though the endpoint does need the token? Am I missing something?

Adlil Yaacob
1 year ago

Thank you for the very detailed explanation! It's the most comprehensive tutorial I have ever gone through! <3