I am looking to transmit a JWT token to my backend using next-auth

In my current project using Next.js, I have implemented authentication with next-auth. This project follows the MERN stack architecture.

I am facing an issue where I need to retrieve the JWT token and send it to my backend server using next-auth along with Axios.

When accessing (session.jwt), it returns undefined.

Below is a snippet from my nextauth.js file:

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { MongoDBAdapter } from '@next-auth/mongodb-adapter';
import clientPromise from '../../../lib/mongodb';

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    session: async ({ session, user }) => {
      if (session?.user) {
        session.user.id = user.id;
      }
      return session;
    },
  },
  adapter: MongoDBAdapter(clientPromise),
  secret: process.env.JWT_SECRET,
  session: {
    jwt: true,
    maxAge: 30 * 24 * 60 * 60, // the session will last 30 days
  },
});

Answer №1

The tutorial provided in their documentation showcases how to store the provider (account) access token in the jwt callback and then add it to the session object:

  callbacks: {
    async jwt({ token, account }) {
        if (account) {
          token.accessToken = account.access_token;
        }
        return token;
      },    
    async session({ session, token, user }) {
      if (session?.user) {
        session.user.id = user.id;
      }
      return {
        ...session,
        accessToken: token.accessToken
      };
    },
  }

Nevertheless, if you prefer using the raw JWT instead of the provider access token on the server side, you can utilize the getToken function:

export async function getServerSideProps(context) {
  const token = await getToken({ req: context.req, raw: true });
// ...
}

Subsequently, to include it in your requests, such as in the authorization header as shown below:

const config = {
    headers : {
        'Authorization' : `Bearer ${token}`
    }
}
axios.get('http://web.com/api', config);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Firebase Issue in Next JS Authentication Flow: Unconfirmed Email Causes "auth/email-already-in-use" Error to Trigger

I have encountered a perplexing issue while setting up user registration with Firebase Authentication in my Next.js application. The problem arises when I try to register a new user with an unverified email address. Instead of following the correct flow to ...

Creating a standalone executable for Node.js without including the entire Node.js framework

Trying to pack a simple hello world script into an executable has led to some challenges. Both pkg and nexe seem to include the entirety of Node.js in the output file, resulting in quite larger files than necessary (around 30 MB). Although EncloseJS was fo ...

Running and storing JavaScript in NEW Selenium IDE: A comprehensive guide

I am facing a challenge with updating my old test scripts that were originally created for the outdated Selenium IDE. The task at hand is to modify them to work with the latest version of Selenium, but I am struggling to make sense of how to handle section ...

Warning on React component listing due to key issue originating from the parent component

Alert: It is essential that each child in a list has a distinct "key" prop. Please review the render method of ForwardRef(ListItem). A child from RecipientsList was passed. I have located this issue using the react-components debugger tool on Chrome. I ad ...

How can I create an asynchronous route in AngularJS?

I implemented route and ngView to display dynamic content, however I received a warning message: The use of Synchronous XMLHttpRequest on the main thread is deprecated due to its negative impact on user experience. For more assistance, please refer to ...

Jest tests are failing because React is not defined

I am attempting to implement unit tests using Jest and React Testing Library in my code. However, I have encountered an issue where the tests are failing due to the React variable being undefined. Below is my configuration: const { pathsToModuleNameMapper ...

Trigger a click event in jQuery to activate a form through a hyperlink

I'm facing an issue where I want to implement a password-reset form based on a certain flag being triggered. Currently, my code is set up to prompt the user to change their password if the password_changed_flag is not present. Depending on the user&ap ...

Button functions properly after the second click

import { Input, Box, Text, Divider, Button } from '@chakra-ui/react'; import { useState } from 'react'; export default function GithubSearchApp() { const [username, setUsername] = useState(''); const [data, setData] = use ...

Guide to Displaying Items in Order, Concealing Them, and Looping in jQuery

I am trying to create a unique animation where three lines of text appear in succession, then hide, and then reappear in succession. I have successfully split the lines into span tags to make them appear one after the other. However, I am struggling to fin ...

Developing a MySQL Community Server-backed RESTful Web Service with the power of jQuery AJAX

I am currently in the process of developing a RESTful Web Service using MySQL Community Server alongside jQuery AJAX Unfortunately, my usage of jQuery AJAX is not functioning as expected. When attempting to add, delete, update a product, or retrieve all p ...

Next.js rewrites the original URL and if the response is 404, a custom 404 page will be displayed

I am working on a Next.js app with a rewrites configuration. The destination URL is external. module.exports = { async rewrites() { return [ { source: '/foo/:slug', destination: 'https://example.com/foo/:slug&apos ...

Could there be a mistake in the way array combinatorics are implemented in JavaScript?

Having encountered the necessity for generating unique combinations when dealing with multiple arrays, I developed this script. While it functions as intended during the combination process, storing the result in a final array yields unexpected outcomes. ...

Finding the Perfect Placement for an Element in Relation to its Companion

Is there a way to achieve an effect similar to Position Relative in CSS using jQuery? I have developed a tooltip that I want to attach to various objects like textboxes, checkboxes, and other text elements. My code looks something like this: <input i ...

Purging the internal buffer of the node stream

Utilizing Node Serialport, I've implemented an event listener to check the data streaming through the connection for correct units. If the units don't match what the user has set, I utilize the .pause() method to pause the stream and inform the u ...

Issue with Ajax form submission functionality not working for sending form data

I recently found the solution to executing a Send Mail script without reloading the page after facing some AJAX issues. However, I am now encountering a problem where the post data is not being received by the PHP script when my form posts to AJAX. For re ...

Guide to putting a new track at the start of a jPlayer playlist

I am currently working on a website that utilizes the jPlayer playlist feature. I am facing an issue, as I need to implement a function that adds a song to the beginning of the playlist, but the existing add function only appends songs to the end of the pl ...

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

What is the best way to include an object within an array that is a property of another object in React.js?

Greetings, I apologize for the somewhat ambiguous title. It was a challenge to find a clearer way to express my thoughts. Currently, I am engrossed in my personal project and have encountered a particular issue. I would greatly appreciate any advice or gu ...

Select a dropdown menu option in Cypress by clicking on it only if it is checked

In this html code snippet, I have multiple elements within a dropdown menu. I am looking for a way to click on an item only if it is selected (has the class selected) or has a check mark in front of the name, as shown in this screenshot. How can I achieve ...

Fetching data from a database for Vue.js using the Summernote editor

I previously inquired about integrating summernote with vue.js and received a helpful response here. It worked seamlessly with v-model binding. However, I encountered an issue when attempting to load data from the database for an edit page. The data was n ...