The system is unable to access the properties of undefined, specifically the 'signedCookies' attribute

I'm encountering an issue with cookies in my code, but I don't believe it's a simple typo.

Error: TypeError - Cannot read properties of undefined (reading 'signedCookies')

// auth.js 
import axios from 'axios'
axios.defaults.withCredentials = true

export const getServerSideToken = (req) => {
  const { signedCookies = {} } = req

  if (!signedCookies) {
    return {}
  } else if (!signedCookies.token) {
    return {}
  }
  return { user: signedCookies.token }
}

const WINDOW_USER_SCRIPT_VARIABLE = '__USER__'

export const getUserScript = (user) => {
  return `${WINDOW_USER_SCRIPT_VARIABLE} = ${JSON.stringify(user)}`
}

export const loginUser = async (email, password) => {
  const { data } = await axios.post('/api/login', { email, password })
  if (typeof window !== 'undefined') {
    window[WINDOW_USER_SCRIPT_VARIABLE] = data || {}
  }
}

export const getUserProfile = async () => {
  const { data } = await axios.get('/api/profile')
  return data
}

The error seems to be originating here and I am unsure about the cause

> 6 |   const { signedCookies = {} } = req
    |          ^
  7 | 
  8 |   if (!signedCookies) {
  9 |     return {}

I'm using this auth.js file in a _document.js file :

//_document.js
import Document, { Head, Main, NextScript } from 'next/document'
import { getServerSideToken, getUserScript } from '../lib/auth'

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const props = await Document.getInitialProps(ctx)
    const userData = await getServerSideToken(ctx.req)

    return { ...props, ...userData }
  }

  render() {
    const { user = {} } = this.props

    return (
      <html>
        <Head />
        <body>
          <Main />
          <script dangerouslySetInnerHTML={{ __html: getUserScript(user) }} />
          <NextScript />
        </body>
      </html>
    )
  }
}

Any help would be greatly appreciated!

Answer №1

While I was following a tutorial video on creating a custom document page in next.js, I encountered this error.

To resolve it, I made use of the req parameter directly within the getServerSideToken function as shown below:

export const getServerSideToken = req => {
    if (!req) {
        return {};
    } else if (!req.token) {
        return {};
    }
    return { user: req.token }
}

This approach provided the desired outcome without any errors. However, I will share a more comprehensive solution in a future update.

I hope you find this information useful.

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

Various Issues Regarding Jquery Libraries

Here's a question on my mind... Currently, in my main file index.php, I have imported jquery 2.0.3 like this: <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> The issue arises bec ...

How can I increase the value of a variable that is displayed within a loop using JavaScript?

I'm struggling to use arrays for this task, even though it should be done that way. When I receive a set of variables through JSON, they look something like this: --variables I don't need... and then: "s_title_a": "---", "s_title_b": "---", "s_t ...

Strengthening JavaScript Security

Throughout the past few years, I have delved into various javascript libraries like Raphael.js and D3, experimenting with animations sourced from different corners of the internet for my own learning. I've obtained code snippets from Git repositories ...

Having trouble with gsap.reverse() not functioning properly when using onMouseLeave event in React

I've been incorporating simple gsap animations into my React application. I have successfully triggered an animation.play() function on onMouseEnter, but for some reason, the animation.reverse() function is not functioning as expected. Here's ho ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...

<select> dropdown menu for selecting specific files opened by JavaScript

Currently, I am converting CSV files into JSON format and then manipulating them to generate arrays that will be used by jQuery to create a graph. My goal is to implement a dropdown menu that allows the user to choose a specific CSV file for graph creatio ...

The functionality in commands.js operates smoothly despite the absence of Cypress and cy being defined

When I input a custom command in commands.js, WebStorm's linter flags both Cypress and cy as undefined without providing any IntelliSense support. Oddly enough, these are properly defined in all integration files. In commands.js Cypress.Commands.add( ...

We are currently experiencing issues with Internet Explorer retrieving data from input type text

My HTML code includes input elements with type="text" like this: <input type="text" class="f_taskname" value=""/> Once the user enters text and hits enter, the following script is triggered: var task_name=$('#filter_body').find('.f_ ...

Tips for automatically closing an accordion tab when a different one is clicked

I've created a unique accordion that allows me to assign a color class to the opened item. However, I'm looking to add a new feature where only one tab remains open at a time, automatically closing any others when clicked. Below is my current co ...

Can you delete angular attributes from HTML elements?

I delved into understanding the inner workings of Angular.js using a basic example. <div ng-app=""> <p>Type something in the input field:</p> <p>Name : <input type="text" ng-model="name" placeholder="Enter name here">< ...

Ways to set the base URL on the development server for a call to react-scripts start

I am facing an issue with configuring my primary PHP server to run the ReactJS dev server created using yarn start within a directory named /reactive on the PHP site (using nginx proxy_pass). The problem is that I cannot set the root of the node server to ...

Jstree: Whenever I refresh my tree, the checkboxes do not reset to default and remain unchecked

After attempting to implement the following code: $("#jstree_demo_div").jstree("destroy").empty(); Although it successfully removes the checked nodes and reloads the tree, it fails to apply the new changes. Any advice on how to resolve this issue would b ...

Tips for parsing a JSON file within my node.js application?

I am working on a node.js service that involves validating JSON data against a schema defined in jsonSchema. Below is the code snippet for my service: app.post('/*', function (req, res) { var isvalid = require('isvalid'); ...

Adjusting the height of the Sencha Touch container to accommodate its content

In Sencha Touch, I have a view that generates a popup box from the right when a button in the bottom toolbar is clicked: Ext.define('TheApp.view.PopupTablet',{ extend: 'Ext.form.Panel', xtype: 'popupbox', confi ...

Deploying an AngularJS 1.x application bundled with Webpack to Tomcat server

I've scoured the depths of Google and combed through the official documentation for Webpack, but I’ve yet to stumble upon a tutorial, guide, or plugin that addresses this particular issue. Does anyone have any experience with this problem, or should ...

Retrieve data from Last.fm API by utilizing both Node.js and Angular framework

I am currently working on implementing the node-lastfmapi track.search method into my project. I have successfully retrieved the results, but I am facing challenges in integrating them into the front end using Angular. My backend is powered by mongoDB and ...

Instructions for incorporating a personalized document in NextJs version 13

In order to enhance the design of my upcoming Next.js 13 project, I am looking to integrate a custom design system package. This particular package necessitates the creation of custom documents within the page directory, as outlined in the official Next. ...

Generating ranges dynamically based on the values in an array

As I receive data from a server, my goal is to categorize it into various buckets for presentation. The dataset appears in the following format: Array [ Object { "name": "1.00", "value": 17, }, Object { "name": "1.01", "value": ...

Issue: The mandatory parameter (slug) was not provided in string format in the getStaticPaths method for the endpoint /posts/[slug]

In my project, I have a [slug].js file with the following code: import Head from "next/head"; import PostContent from "../../components/posts/post-detail/post-content"; import { getPostByName, getAllPosts } from "../../helpers/api- ...

Animating avatars with Three.js

Seeking some guidance on utilizing the three.js library for creating animations. Specifically, I am interested in animating an avatar that has been exported from Blender to Collada format (.dae), to move an arm or a leg. I would like to achieve this anim ...