The issue with getting a token from Next-auth on the server side persists

Currently, I am working on an application using Next.js and implementing authentication with NextAuth. However, I am encountering an issue with the getToken function not working properly on the server-side.

I have double-checked my callbacks configuration:

callbacks:{
    async jwt({ token, user }) {
      return { ...token, ...user }
    }
}

I have also attempted to pass the NextAuth secret as an argument in this way:

const token = await getToken({
      req: request,
      secret: process.env.NEXTAUTH_SECRET
    })

    console.log(token)

Every time I call getToken, it returns null, which has prompted me to create a test endpoint to investigate further:

import { getToken } from 'next-auth/jwt'

export default async function handler(req, res) {
  const token = await getToken({ req })

  res.status(200).json({ user: token })
}

Additionally, I have created a page for testing purposes:

const test = props => {
  const { token } = props

  return (
    <div>
      <button onClick={() => console.log(token)}>teste</button>
    </div>
  )
}

export async function getServerSideProps(context) {
  const tokenRes = await fetch(`${process.env.NEXT_PUBLIC_BASE_PATH}/api/test`)
  const token = await tokenRes.json()

  console.log(token)

  return {
    props: {
      token: token
    }
  }
}

export default test

The object passed to pageProps shows a null token.

Strangely, when I access the endpoint directly in the browser, I receive the expected token: my token '-'.

I am determined to use getToken effectively on the server-side and middleware to retrieve my token. What could be causing this unexpected behavior? Any guidance or advice would be greatly appreciated!

Thank you in advance for your help!

Answer №1

Dear Reader,

An issue arises when fetching data through my endpoints using fetch(url). When getServerSideProps calls fetch, the cookie is not automatically transmitted.

To address this problem, it is important to manually pass the cookie in the following manner:

export async function getServerSideProps(context) {
  const { req } = context

  const tokenRes = await fetch(`${process.env.NEXT_PUBLIC_BASE_PATH}/api/test`, {
    headers: {
      Cookie: req.headers.cookie
    }
  })

  const token = await tokenRes.json()

  console.log(token)

  return {
    props: {
      token: token
    }
  }
}

By implementing this approach, getToken functions correctly.

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

Retrieving data using Next.js 'catch-all' routes

Using Next.js 10, you now have the ability to create a catch all route that looks something like this: [...id].tsx. This enables the development of dynamic pages that can match paths such as /example, /example/new, and /example/new/latest. However, one is ...

Background image not displaying in new tab after Chrome extension installation

I have been developing a Chrome extension that alters the background image of a new tab. However, I have encountered an issue where the background image doesn't change the first time the extension is loaded. This problem has also occurred very occasi ...

Retrieve the access token from next_auth in order to utilize it with googleapis

Looking for guidance on obtaining an access_token from next_auth to utilize with googleapis? I am developing a CRUD application that stores data in Google Drive, utilizing nextjs and next-auth for OAuth integration with Google. After following instructions ...

What is the way to instruct Mongoose to exclude a field from being saved?

Is there a way in Mongoose to instruct it to not save the age field if it's null or undefined? Or is there a method to achieve this in Express? Express router.put('/edit/:id', function(req, res) { Person.findOneAndUpdate({ _id: req.p ...

A guide to building a dynamic form slider that showcases variable output fields with Javascript

I'm interested in creating a Slider Form that shows different output fields when sliding, using Javascript. Something like this: Could anyone provide suggestions on how to achieve this or share any links related to something similar? I haven't b ...

Error encountered when attempting to send JSON data with special characters via a POST or PUT request using node.js's http.request()

While attempting to use the node.js http module to PUT a JSON data into CouchDB, I encountered an issue. The JSON included a special character "ä" which caused CouchDB to respond with an "invalid_json" error. However, once the special character was remove ...

A guide on utilizing nodejs to automatically open the default browser and direct it to a specific web address

I am currently developing a program using Node.js. One of the features I aim to implement is the ability to launch the default web browser and direct it to a particular URL. I want this functionality to be compatible across Windows, Mac, and Linux operat ...

Integrating a search box with radio buttons in an HTML table

I am currently working on a project that involves jQuery and a table with radio buttons. Each button has different functionalities: console.clear(); function inputSelected(val) { $("#result").html(function() { var str = ''; ...

Enhance dynamically generated HTML using jQuery Mobile

Using jQuery Mobile version 1.2.0 I am dynamically generating HTML using JavaScript ($(selector).html(content)), adding it to the DOM, and then displaying it ($.mobile.changePage()). After that, I make an AJAX call, retrieve some data, and re-generate th ...

What could be the reason behind jQuery replacing the entire span with .text?

I am dealing with the following HTML code snippet: <p><input id="revenue" type="text" value="100000" /><span id="howmuch"><a href="" class="ka_button small_button small_cherry" target="_self" style="opacity: 1; "><span>How Mu ...

Delete an entry in a singular mapping in a one-to-one connection [TypeORM]

Is there a way to remove an index from a one-to-one relationship in TypeORM? @OneToOne(() => Customer, { cascade: true }) @JoinColumn({ name: 'customer', referencedColumnName: 'uid' }) customer: Customer I searched the d ...

What is the method for swapping out the <button> element with the enter key?

I have a webpage where users can post status updates, and other users can comment on these statuses by typing in the textbox and clicking the 'Reply' button. However, I would prefer to remove the button so users can simply press the enter key to ...

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...

How to identify generic return type in TypeScript

My goal is to develop a core dialog class that can automatically resolve dialog types and return values based on the input provided. I have made progress in implementing this functionality, but I am facing challenges with handling the return values. Each ...

exploring various dynamic elements using jquery

If you need some help figuring this out, take a look at the JSFiddle here. I've set it up for users to input any data they want in the text box, choose a table from set one, and then click the "submit" button to send it. <div> <Div> < ...

Creating a merged object from a split string array in TypeScript

I possess an array containing objects structured as follows; const arr1 = [ {"name": "System.Level" }, {"name": "System.Status" }, {"name": "System.Status:*" }, {"name": "System.Status:Rejected" }, {"name": "System.Status:Updated" } ] My object ...

SignalR's postback interrupts the functionality of jQuery actions

On my screen, I have a widget that updates data and changes its class based on server-side interactions. It also responds to mouse clicks. To notify multiple clients of updates simultaneously, I'm using SignalR. The problem arises when I wrap everythi ...

Is the Ajax DataType response JSON showing as "OK" but the output is blank?

So, I'm facing a challenge here. I have a basic jQuery Ajax request that isn't working when I set the DataType to "JSON". var form_data = { "id": msg, "token": token }; $.ajax({ type: 'POST', url: "ajax.php", ...

What is the process for updating the ID within a Select2 ajax script function?

I am facing an issue with my select2 ajax script. The unique_ID in my table field is named "no", which is causing me to be unable to select an item in Select2 drop down. However, when I changed the name of my database table field from "no_donatur" to "ID", ...

Is it possible to successfully pass a parameter from a servlet to a JavaScript function, but encounter issues when trying to view the database

In my view servlet, I am displaying user data from the database in a table. Each row of the table has buttons that allow users to change the cells in that row to text boxes. The issue I am encountering is that when I retrieve the data and loop through to ...