Why is it difficult to retrieve session information in API route using Next.js and NextAuth?

As a newcomer to Next.js and NextAuth, I might be overlooking something obvious here. Currently, I am using the next-auth email provider for a magic link authentication process. The authentication and redirection are working smoothly as I can see the cookies in the Application tab of Chrome dev tools. In my home page's getServerSideProps(), I am able to console log the session like this:

const session = await unstable_getServerSession(context.req, context.res, authOptions)

Everything seems to be functioning properly until I try to access a protected route where the session is null, resulting in a 401 error. Below is a snippet of code for a protected route:

import prisma from 'Utilities/PrismaClient'
import { logDBError } from 'Utilities'
import { unstable_getServerSession } from 'next-auth/next'
import { authOptions } from 'pages/api/auth/[...nextauth]'

export default async function handler (req, res) {
  const session = await unstable_getServerSession(req, res, authOptions)
  console.log(`SESSION_FROM_BOARD_ROUTE: ${JSON.stringify(session)}`) // SESSION_FROM_BOARD_ROUTE: null
  const token = await getToken({ req })

  if (!session) {
    console.log(401)
    return res.status(401).json({ board: {}, tasks: [] })
  }
...
// GET
// POST
// etc, etc.
}

This is how my [...nextauth].ts file looks like:

// src/pages/api/auth/[...nextauth].ts:

import NextAuth from 'next-auth'
import EmailProvider from "next-auth/providers/email";
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import prisma from 'Utilities/PrismaClient'
import type { NextAuthOptions } from 'next-auth'

export const authOptions:  NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    EmailProvider({
      server: {
        host: process.env.EMAIL_SERVER_HOST,
        port: process.env.EMAIL_SERVER_PORT,
        auth: {
          user: process.env.EMAIL_SERVER_USER,
          pass: process.env.EMAIL_SERVER_PASSWORD
        }
      },
      from: process.env.EMAIL_FROM
    }),
  ],
}
export default NextAuth(authOptions);

Furthermore, here is the page responsible for making API requests (handleFetchData):

import React, { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import Board from 'Components/Screens/Board/Board'
import { useRouter } from 'next/router'
import axios from 'axios'
import { getBaseUrl } from 'Utilities'
import { hydrateTasks } from 'Redux/Reducers/TaskSlice'

const BoardPage = (props) => {
  const router = useRouter()
  const dispatch = useDispatch()

  useEffect(() => {
    async function handleRouteChange() {
      const { boardId } = router.query
      const { board, tasks } = await handleFetchData({ boardId })
      dispatch(hydrateTasks({ board, tasks }))
    }
    handleRouteChange()
  }, [router])

  return (
    <Board {...props}/>
  )
}

const handleFetchData = async ({boardId, req}) => {
  const baseUrl = getBaseUrl(req)
  return axios.get(`${baseUrl}/api/board/${boardId}`, {
    withCredentials: true
  })
    .then(({data}) => data)
    .catch(err => { console.log(err)})
}

export async function getServerSideProps ({ query, req }) {
  const { boardId } = query
  const { board, tasks}  = await handleFetchData({boardId, req}) ?? {}
  return { props: { board, tasks } }
}

export default BoardPage

Your help is greatly appreciated.

Answer №1

After digging around, I finally stumbled upon the solution on Stack Overflow: It turns out that setting cookies is crucial when sending an HTTP request from the server side!

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

Is it possible for jQuery to navigate to a different page, extract around 10 links, and then incorporate them into the original page?

Apologies if the title of my question is unclear, allow me to clarify. I'm interested in exploring the possibility of a specific task and would appreciate guidance on how to proceed. While I haven't attempted it myself yet, I am eager to learn mo ...

"Trouble With JSON and ASP.NET WebMethod: Server-Side Method Not Executing

I am attempting to send parameters to my code behind using the WebMethod. Although I am successfully reaching the end of ajax, the method in my aspx.cs code behind is not being called and I am encountering an error. Operation failed! Details: '[ob ...

IE Troubles: Timer Function Fails in Asp.Net MVC

I implemented the following code snippet: @Using Ajax.BeginForm("Index", New AjaxOptions() With { _ .UpdateTargetId = "AnswerSN", .HttpMethod = ...

Automatically submitting a Google Form using the Google Forms API in conjunction with Google Apps Scripts

Is it possible to integrate a third-party app with Google Forms API and Google Apps Script in order to create timed quizzes that automatically submit once the time limit has been reached? ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

Is there a way to transform a regular CommonJS declaration into an ECMAScript import when it is making multiple requires in a single line?

As a beginner in JavaScript, I am interested in converting this line into an import statement: var sass = require('gulp-sass')(require('sass')); I have successfully converted the other requires into imports but I'm struggling wit ...

Prevent span/button clicks by graying them out and disabling the ability to click using HTML and JQuery

I am facing a challenge with my two spans that reveal specific information when clicked. I want to make one span appear as a disabled button (greyed out) when the other span is clicked. I tried using $("#toggle-odd").attr("disabled", tr ...

Struggling with organizing my code in node.js - it's all over the place and not very reliable. How should I tackle this

Can anyone help me troubleshoot an issue I'm facing with code that writes to the console late or in random order? var request = require('request'); var vFind = 'HelloWorld'; var vFound = false; var vSites = ['http://www.youtu ...

Navigating through arrays to access nested objects

Currently, I am attempting to retrieve a specific field within a nested array using the following code: var array1 = []; const data = { [userId]: [{ id: id, name: fullName, email: userEmail }, ], ...

Tips on using an array filter in AngularJS ng-repeat

I have successfully used ng-repeat to display my data. Within the ng-repeat result set, one of the data fields is an array of items. Example: {x:1, y:[2,3,4]} I want to filter the data based on the values inside the array. Filtering by non-array data is ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

What is the name of the scrolling header effect achieved in the following?

I've been seeing a lot of people using a unique header effect lately and I'm curious to learn more about how it's done. Can anyone explain the process behind achieving this effect, what it's called, and if there are any good tutorials a ...

Ensuring a dependable detection of WebSocket connection status

I've been researching how to create a dependable method for recovering a WebSocket connection. After exploring various options, I discovered that one approach involves sending heartbeats (ping/pong) to the server and monitoring if the entire pong is ...

Create a canvas that extends the width and height of its parent container

Looking to create a rectangular canvas that acts as a progress bar, but struggling with setting the width and height to 100%. It doesn't seem to fill the parent container properly. Check out this example below: http://jsfiddle.net/PQS3A/ Is it fea ...

hiding form fields using javascript

As a beginner in javascript, I am facing a challenge with a set of checkboxes in an HTML form. These checkboxes are generated dynamically from a python script. Among them, there is a checkbox labeled "N/A" that I want to hide automatically when any other c ...

What is the best way to enforce a required selection from one of the toggle buttons in a React form?

Is there a way to require the user to click one of the toggle buttons in a react form? I need to display an error message if the user submits the form without selecting a button. I tried using the "required" attribute in the form but it didn't work. H ...

Populate object values dynamically through function invocations

Currently, I am involved in a project with a VueJS application that incorporates the following helper class and method: class BiometricMap { static get(bioType) { if (!bioType) { return BiometricMap.default(); } const bioTypes = { ...

Error: The variable "xxxx" is undefined. Attempting to assign a PHP variable to JavaScript

I have a URL mapped like this: xxx/app/reset.php?token=fc832c73b6695a782cb1040b48a1ac2e6c33aaf2&action=reset After assigning it as follows: $token = $_GET['token']; $token_ = "_".$token; I store it in a JavaScript variable like so: var ...

Fleeing from the clutches of the $.ajax({ success: function() }) labyrinth

There is a common scenario where AJAX responses dictate the flow of actions, often leading to nested AJAX responses. However, this results in a clutter of presentation-specific code within the success() callback: $.ajax({ ... success: function ...

Calculate the number of rows in a table that contain identical values

I have a puzzling issue that has been on my mind. I currently have an SQL statement that selects specific rows from my database and displays them in an HTML table, which is functioning properly. However, I now need to determine how many rows have the same ...