Next.js Discord

Discord Forum

Data fetching and passing jwt from next-auth

Unanswered
AM posted this in #help-forum
Open in Discord
AMOP
Hello i do have custom backend ( nestjs ) that handles my api calls, I have managed to integrate next-auth and store my accessToken there and everything works good. After I continue building custom api calls like update-password and so on. How ever i need to get the token from next-auth and pass it as a Authorization header.

I have came up with this solution:

import { getSession } from 'next-auth/react';
import { NextApiRequest } from 'next';



const baseUrl = 'http://localhost:3004/api/auth/password';

enum API_ERRORS {
  UPDATE_PASSWORD = 'Failed to update password'
}

const getAccessToken = async (req: NextApiRequest) => {
  const session = (await getSession({ req })) as any;
  return session?.accessToken;
};

export const updatePasswordApi = async (data: {
  oldPassword: string;
  newPassword: string;
}) => {
  const accessToken = await getAccessToken();

  const response = await fetch(baseUrl, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer {jwt}`
    }
  });

  if (!response.ok) {
    throw new Error(API_ERRORS.UPDATE_PASSWORD);
  }

  return response.json();
};


but the problem is that i'm really not sure how to grab the token from next-auth and pass it, how to handle such scenario or i'm doing something completly wrong

0 Replies