0

Can I build authentication system between django and nextjs 13 ?

If yes, How can I do that ? I'm really stuck

I wanted to use JWT token based authentication but because nextjs 13 uses server components I didn't know how and where can I store access and refresh tokens.

Thanks..

Saif
  • 1
  • 1

2 Answers2

0

Next.js and Django JWT Authentication | Part 1 - Backend API

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

Karthik
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Kins Jul 27 '23 at 09:36
0

you can store jwt token in secure cookies or localstorage

Secure cookies is safers as compare to localstorage

// utils/auth.js

import { parse, serialize } from 'cookie';

const MAX_AGE = 60 * 60 * 24 * 7; // 1 week in seconds

// Function to set secure cookies
export function setAuthCookies(res, accessToken, refreshToken) {
  const accessTokenCookie = serialize('access_token', accessToken, {
    maxAge: MAX_AGE,
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production', // Set "secure" to true in production
    path: '/',
  });

  const refreshTokenCookie = serialize('refresh_token', refreshToken, {
    maxAge: MAX_AGE,
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production', // Set "secure" to true in production
    path: '/',
  });

  res.setHeader('Set-Cookie', [accessTokenCookie, refreshTokenCookie]);
}

// Function to get JWT tokens from cookies
export function getAuthCookies(req) {
  return parse(req.headers.cookie || '');
}

After a successful login or registration, you can use setAuthCookies to store the tokens in the response: // After successful login or registration

import { setAuthCookies } from '../utils/auth';

// Assuming you have accessToken and refreshToken from the server response
setAuthCookies(res, accessToken, refreshToken);

To access the tokens on subsequent requests, you can use getAuthCookies in your API functions:

import { getAuthCookies } from '../../utils/auth';

export default async function handler(req, res) {
  const { access_token, refresh_token } = getAuthCookies(req);

  // Now you can use access_token and refresh_token for authentication
}
Lokesh
  • 1
  • 2
  • can I use this way to handle tokens with server components like when I request a dynamic page that uses fetch api to call api that needs authorization get data ? – Saif Jul 24 '23 at 17:42