The user in req.session is not defined within a Next.js iron-session

I'm currently working on a dashboard for our team's bot that utilizes next.js and iron-session.

However, I've run into an issue where req.session.user is showing up as undefined when I try to save the session. How can I go about fixing this error?

Below is the snippet of code where the error occurs:

page/auth.js:

Auth.getInitialProps = async ({ query }) => {
  //console.log(query.code)
  const result = await axios.get(`https://lunasite.prnm789.repl.co/api/sign/in?code=${query.code}`)
  const { access_token, refresh_token } = await result.data
  const newsession = await axios.post(`https://lunasite.prnm789.repl.co/api/session/new`, {
    access_token: access_token,
    refresh_token: refresh_token
  })
  ...
}

page/api/session/new.js:

import { withIronSessionApiRoute } from 'iron-session/next'
import { sessionOptions } from '../../../lib/config'

export default withIronSessionApiRoute(userRoute, sessionOptions)

async function userRoute(req, res) {
  if (req.method == "POST") {
    const { access_token, refresh_token } = req.body
    ...

    try {
      req.session.user = {
        isLoggedIn: true,
        access_token: access_token,
        refresh_token: refresh_token
      }
      await req.session.save()
      ...
    } catch(e) {
      ...
    }
  } else {
    ...
  }
}

lib/config.js:

export const sessionOptions = {
  cookieName: "luna_cookie",
  password: process.env.sessionCookiePass,
  cookieOptions: {
    secure: process.env.NODE_ENV === "production",
    maxAge: 604800 - 60
  },
}

page/api/session/get.js:

import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "../../../lib/config";

export default withIronSessionApiRoute(getRoute, sessionOptions);

function getRoute(req, res) {
  res.send(String(req.session.user))
}

Answer №1

Could you verify if the front-end domain and network request URL match up? I encountered a similar issue when I set the base URL for my requests using NEXT_PUBLIC_VERCEL_URL, which provided an automatically generated URL for that specific deployment. In short, my session was being saved on the main domain while my requests were directed somewhere else. Once I switched to using an absolute path, all of my issues were resolved.

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

How can the Material UI select component be customized to automatically scroll to the top when all items are selected?

After implementing the material ui select feature, I observed that when all items are selected, closed, and then reopened, the scroll position is automatically moved to the end. Is there a way to prevent this and keep it at the top? Current display: http ...

JavaScript: Find options in a datalist that correspond to user input

One of the features I am working with is a text input that utilizes a datalist. The content of this datalist is populated dynamically using PHP: <input type="text" name="city" list="cities" id="city"> <datalist id="cities"> <?php ...

Unable to unregister event listener using RemoveEventListener function

After attaching an event listener to my SVG image to run some code once the image is loaded, I encountered a bug in my SVG generation code that sometimes prevents the file from loading. In this scenario, when the user clicks another button, I want to remov ...

Top methods for handling special characters in a database

My mysql database is filled with json data that is then used in angularjs for display purposes. Some of the text within the database includes escaped quotes and double quotes, for example: Do you possess at least a bachelor\'s degree in child ...

Guide on managing opening and closing of dialogs in a Vuetify data table

We have developed an application for a staffing agency that allows the Admin to view Users in a Vuetify data table. However, when displaying User Notes in the table, we encounter issues with long notes not fitting well within a table cell. Our goal is to i ...

In absence of javascript, AJAX comes to the rescue for retrieving data

Is there a way to handle an AJAX get request if the browser does not have JavaScript enabled? Imagine clicking on an image thumbnail that leads you to a controller returning image details and a zoomed-in photo. I aim to use AJAX to display the enlarged p ...

AngularJS enhances user experience by allowing textareas to expand upon click

I am just starting to learn about angular.js and I'm wondering how to add a text area when clicking on an image. ....... ..... ..... </thead> <tbody> <tr ng-repeat="stu in Studentlist"> <td>{{stu.rollno}}</td> <td> ...

Implementing multiple modules within a shared parent route in Angular

Currently, I am seeking a method to load multiple modules under the same path in Angular. Let's say I have three modules: AModule, BModule, and CModule, each with its own RouterModule.forChild call. My goal is to combine these modules under the route ...

Display content exclusively in PDF format

On my HTML page, I have two sections - one for inputting values and the other for viewing a PDF. To ensure that the PDF view is hidden until explicitly requested, I need it to remain invisible by default. It should only appear as a PDF when someone clicks ...

Searching for the object that occurs an uneven number of times

Currently, I am tackling a challenge on Codewars that requires identifying the element in an array that occurs an odd number of times. The current solution I have successfully passes 3 out of 6 tests. function findOdd(A) { //happy coding! let odd = &qu ...

How can I efficiently extract specific data from JSON using AngularJs?

In my array (_users), there are JSON objects. { "User": { "userid":"19571", "status":"7", "active":"1", "lastlogin":"1339759025307", "Stats": [ { "active":"1", "catid":"10918", "typeid":"71", ...

My month sorting function is designed to work efficiently, although it seems to only be effective on the first

I am currently using a combination of JavaScript and Angular to sort through my data. Initially, I attempted to filter the data by month and it worked as expected the first time. However, for some reason, it stopped functioning properly afterwards, causing ...

Guide to organizing a one-to-one object map within Angular JS ng-repeat

Is there a way to organize a one-to-one object map in angular.js using filters (or any other technique) while working within an ng-repeat loop? This is what I currently have: obj:{ a:3, c:5, d:1, g:15 } Basically, I want to achieve s ...

The "getJson" function fails to execute when attempting to run a Python

I've come across a simple code snippet, but for some reason, my getjson function isn't working as expected. My Python script properly prints a JSON encoded value. Does anyone have any suggestions? HTML <!DOCTYPE html> <html> <h ...

What is the best way to display the HTML content being received from the database in the DOM?

I have received an object in this format [ { "BET": 57630343, "CUSTOMER": 181645, "SPORT": "MLB", "XX_FILL OPEN": "<button class=\"btn\" onclick=\"fillOpen(57630343)\">Fill Open</button>", "XX_VIEW": n ...

Instructions for sketching a square at predetermined coordinates

Looking for a simple function to draw a box at specific coordinates x and y. I've searched for guides, but they all seem to provide excessive or insufficient information. Thanks in advance! ...

Utilize the power of Wikitude within an Angular 2 application

I am currently working on integrating Wikitude Architect View in Angular 2 by referring to the code at this link. My goal is to implement this code in an Angular 2 compatible way. import * as app from 'application'; import * as platform from & ...

Having trouble downloading Next.Js as I continuously encounter the error message "Module Not Found."

Struggling to download Next.Js and encountering the error message "Cannot find Module" view image here Any assistance would be greatly appreciated as this is time sensitive. I attempted to reinstall Node.js but unfortunately, it did not resolve the issue ...

Is there a way for rainyday.js to utilize a CSS background image as its background?

I have a simple website with a fixed, full-sized background set using CSS. I am trying to incorporate rainyday.js to create a rain effect over the entire site, including the text. Currently, I am only able to get rainyday.js to display rain over a small s ...

The condition for "Else" always remains untouched

This snippet is a segment of my partial view content - <div class="form-group row"> <label for="email" class="col-sm-2 form-control-label">Email address</label> <div class="col-sm-9"> <input type="email" class=" ...