The situation arose where Next.js could not access the cookie due to

Hi there, I'm new to web development and recently encountered a challenge with my next.js app. I'm currently following Brad Traversy's course on udemy to learn basic CRUD functions.

In this component, I am trying to fetch user data from my Strapi backend.

import React from 'react'
import Layout from '../components/Layout'
import { parseCookies } from '@/helpers/index'
import { API_URL } from '../../config'

const Dashboard = ({ events }) => {
    return (
        <Layout title='User Dashboard'>
            <h1>Your events</h1>
            {events && events.length && events.map((el, i) => <div>{el.name}</div>)}
        </Layout>
    )
}

export default Dashboard

export async function getServerSideProps({ req }) {
    const { token } = parseCookies(req)

    const res = await fetch(`${API_URL}/events/me`,
        {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${token}`
            }
        })

    const events = await res.json()

    return {
        props: {
            events
        }
    }
}

The helper method is supposed to extract the cookie from the request and return the token to getServerSideProps.

import cookie from 'cookie'


    export function parseCookies(req) {
        console.log('///// REQ IN HELPER', cookie.parse(req.headers.cookie))
        return cookie.parse(req ? req.headers.cookie || '' : '')
    }

However, instead of returning a token, the method returns the following:

{
  _xsrf: '2|07438526|dd1d3c86869ab7209b159b127acbead9|1629292796',
  'username-localhost-8888': '2|1:0|10:1629300070|23:username-localhost-8888|44:OThhNzc0YWY=...
}

Here is how I set the cookie after login:

import { API_URL } from '../../config/index'
import cookie from 'cookie'


export default async (req, res) => {
    if (req.method === 'POST') {
        const { identifier, password } = req.body

        const strapiRes = await fetch(`${API_URL}/auth/local`,
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ identifier, password })
            })

        const data = await strapiRes.json()

        if (strapiRes.ok) {

            res.setHeader('Set-Cookie',
                cookie.serialize('token', data.jwt),
                {
                    httpOnly: true,
                    maxAge: 60 * 60 * 24 * 7,
                    sameSite: 'strict',
                    path: '/'
                })

            res.status(200).json({ user: data.user })
        } else {
            res.status(data.statusCode).json({ message: data.message[0].messages[0].message })
        }
    }
    else {
        res.setHeader('Allow', ['POST'])
        res.status(405).json({ message: `Method ${req.method} is not allowed` })
    }
}

I believe the issue with getting an undefined cookie in the dashboard component might be due to server-side storage settings. Can anyone provide insights on how to resolve this?

Answer №1

After troubleshooting, I identified my error - for those facing the same issue, here's where I went wrong: The call to cookie.serialize was incorrect; the object with the options should have been passed as an argument of cookie.serialize instead of within setHeader.

Incorrect version

res.setHeader('Set-Cookie',
                cookie.serialize('token', data.jwt),
                {
                    httpOnly: true,
                    maxAge: 60 * 60 * 24 * 7,
                    sameSite: 'strict',
                    path: '/'
                })

Correct version:

res.setHeader('Set-Cookie',
                cookie.serialize('token', data.jwt,
                {
                    httpOnly: true,
                    maxAge: 60 * 60 * 24 * 7,
                    sameSite: 'strict',
                    path: '/'
                }))

Answer №2

While troubleshooting, I discovered a solution that may assist you in resolving your issue. It turned out that there was a faulty cookie stored in my browser, causing my application to crash. Once I removed this cookie, everything started functioning properly.

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

Activate automatic selection when the input field is disabled

How can I enable auto-select for text in an input field even when it is disabled? Currently, the auto select feature doesn't work when the field is disabled. Here is my HTML: <input type="text" class="form-control" ng-model="gameId" select-on-cli ...

steps to remove the border of the select box in MUI component

i am struggling to disable the border on the select box and change the color of the label text when focused or blurred i have attempted it but have been unsuccessful i am not very skilled at Mui component customization this is the image that i desire ht ...

Establish an HttpOnly cookie using JavaScript

Is it possible to convert a non-HttpOnly cookie into an HttpOnly cookie using JavaScript? ...

I recently installed bootstrap, jquery, and popper.js on my live server, but to my surprise, nothing was appearing on the screen. Despite compiling the

After successfully installing bootstrap, jquery, and popper.js, I encountered an issue on my live server where nothing was displaying. Oddly enough, no errors were detected after compiling the code. import { createApp } from 'vue' import App from ...

Having trouble transmitting data with axios between React frontend and Node.js backend

My current challenge involves using axios to communicate with the back-end. The code structure seems to be causing an issue because when I attempt to access req.body in the back-end, it returns undefined. Here is a snippet of my front-end code: const respo ...

The node.js express app.get and app.post are currently malfunctioning

I have encountered an issue with my Express JS code. Currently, I am using app.use and everything works perfectly. However, when I try to use app.post or app.get instead of app.use, the code stops working and my IDE (WebStorm) does not recognize these meth ...

Angucomplete-alt fails to display dropdown menu

On my website, there is a textarea where users need to input the name of a group project. The goal is to implement autocomplete functionality, so as users type in the project name, a dropdown menu will appear with suggestions of existing projects to assist ...

Tips on invoking a mixin within a Jade template showcased in a Node/Express endpoint

I'm currently developing a component that I plan to use multiple times on a website through a Jade template. This is how my route is set up: router.get('/', function(req, res, next) { res.render('indicators',{category:"", num ...

What could be causing my data to shift after refreshing in Firefox with the F5 key?

My webpage has four tables, each containing rows with two text boxes filled with numeric values from the server. However, something peculiar occurs. When I add data to a row, let's say row 1, and then refresh the page, two values are mysteriously mov ...

Which is better: NextJs or just pure ReactJs?

Although I recognize the advantages of NextJs such as SSR (which supports SEO), built-in routing, and image rendering optimization, it seems that using a state management library like Redux or Thunk is still necessary for managing app-wide state. While the ...

The onchange() function for a multi-checkbox dropdown is failing to work as

Issue with Multiple Drop Down Checkbox Functionality: The first parameter is always received as undefined, and the onchange event only captures the value of the first checkbox selected. <select name="multicheckbox[]" multiple="multiple" class="4colacti ...

Retrieve the encrypted URL

I'm facing an issue with extracting parameters from an encrypted URL. When using the queryparams function, it only retrieves a portion of the URL after being decrypted. For instance, consider this example URL: http://localhost:4200/househouse? MGRjYjQ ...

In the realm of Laravel, Vue, and Javascript, one may question: what is the best approach to omitting a key

When working with JSON data, I encountered a problem where leaving some keys unfilled resulted in incorrect results. I want to find a way to skip these keys if they are not filled. I have shared my code for both the backend and frontend below. Backend La ...

Error: The reference property 'refs' is undefined and cannot be read - Next.js and React Application

Here is my code for the index page file, located at /pages/index.js import { showFlyout, Flyout } from '../components/flyout' export default class Home extends React.Component { constructor(props) { super(props); this.state = {}; } ...

The material-ui library always registers Event.ctrlKey as true

When using the Table Component from the material-ui library, I encountered an issue with the multiSelectable feature. Setting the value of multiSelectable to true allows for multiple selections, but the behavior is not what I expected. By default, the sel ...

Is there a way to display the form values on the table once it has been submitted?

I'm struggling with my form input not showing up under the table headings after submission. I've reviewed the code multiple times, but can't figure out what's causing the issue. If you have any suggestions on how to write the code more ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...

Setting up React-Leaflet 4 in conjunction with NextJS 14 for effective functionality

Creating a leaflet map in a NextJS 14 App comes with its fair share of challenges: NextJS 14 defaults to Server Side Rendering (SSR), which isn't compatible with leaflet Webpack bundling used by NextJS 14 can cause issues with leaflet icons The nece ...

How can I turn off shadows for every component?

Is it feasible to deactivate shadows and elevation on all components using a configuration setting? ...

Accessing the selected list item from an unordered list in Vue.js

How can I capture the selected item from a dropdown-style list and perform operations based on that selection? In my list, each item is associated with a key for unique identification, except for 'Create New Filter'. I am seeking guidance on ho ...