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

The Ajax function fails to trigger during the first load of the page

Note: Kindly refer to the update at the end of this question before proceeding. The problem described is specific to IE 11 and emerged after a recent Windows update. Following the installation of 5 updates, including one for IE, I removed the latter hopin ...

What is the best way to show the contents of an array after making a getjson request?

My function makes two getJSON calls and writes the responses to an array. At the end of the second getJSON call, I used the code snippet below: alert(files.length); print_r(files); console.log(files); However, the alert shows the correct number of items ...

Allow-Origin-Control, handler.php for emails, and form validation script

I encountered a strange bug recently. There's been some issues with the HTML5 template I downloaded, specifically related to the contact form and MailHandler.php file. Despite having both files in the same directory, when inspecting element in Chrome, ...

How to inject a variable into an AngularJS service that utilizes both $http and $interval functions?

Struggling with $http and $interval, I stumbled upon this code. http://embed.plnkr.co/fSIm8B/script.js I forked it here: http://plnkr.co/edit/Al8veEgvESYA0rhKLn1q To make it more functional, how can I pass a variable to the service? Here is the broken ...

Avoid the situation where the prop overrides the existing data

I am facing a challenge with vue.js as a beginner. I have an array filled with objects that I send through props to my router-view. Within one of my router-view components, I am using this array in multiple functions by referencing it with 'this.data ...

Is it possible to toggle the content of a post within a "post" title on a webpage?

I am currently working on a project where I want to display all "posts" titles on a specific page. When someone clicks on a post title, the content should toggle below it. If the title is clicked again, the content should hide. With the help of the WP-Arc ...

Securing multiple routes in AngularJS using resolve for authentication

How can I authenticate users for all routes in my application without having to specify it individually? Is there a global way to handle authentication for all routes, so that I don't have to include the following code on each $routeProvider.when() c ...

Unable to dispatch an event from a child component to a parent component in Vue.js

Within my parent component, I retrieve an array of strings from an API and pass it down to the child component. The child component then displays this data as a dropdown list. When an item is selected from the dropdown, I aim to assign it to a specific var ...

What is the process for selectively adding interceptors to app.module?

After searching through various topics, I have not found a solution that addresses my specific issue. To provide some context, we have an Angular App that operates in two modes - one mode uses one API while the other mode utilizes a different API. My goal ...

Encountering an issue with postman where properties of undefined cannot be read

I am facing an issue while trying to create a user in my database through the signup process. When I manually enter the data in the create method, it works fine as shown below: Note: The schema components are {userName:String , number:String , email:Stri ...

adjusting the size and positioning of an image within a parent div using React

Hey everyone, I'm a newcomer to the world of React. Currently, I'm working on a website and everything seems to be falling into place nicely. However, I've encountered a little hiccup. My goal is to write code within my SCSS folder that will ...

What is the best method to erase data from an AutoComplete Box when clicking?

I have incorporated the Material UI AutoComplete component which can be found here. Below is my code snippet: <Autocomplete open={showUniSuggs} onOpen={this.props.getUniversityOptions} onChange={(event, value) => this.props.handleUniversi ...

Variations in ajax requests coupled with a polling mechanism

Suppose the initial ajax call is made right away, and the function called by the controller keeps looping until it reads something, as shown below: def FirstAjax(): while True: if something is read: val = something brea ...

Is there a way to specify a custom error type for returned data in rtk query?

Encountered a type error while using rtk query with the following content : Property 'data' does not exist on type 'FetchBaseQueryError | SerializedError'. Property 'data' does not exist on type 'SerializedError' ...

What is the best way to hide the jQuery modal I created?

Hello everyone! Currently, I am working on coding a simple JS modal that can be opened and closed smoothly. The issue I am facing is related to adding a click function to (.black-overlay) in order to fade out everything and close the modal. <div class ...

Unable to dispatch actions within the mounted lifecycle hook in Vuex?

Can anyone explain why the json data I fetch with axios is not populating my state.pages as expected? Interestingly, when I make a change to the file and vite reloads, the data appears on the page. However, it disappears again upon refreshing the browser. ...

Flot causes the x-axis display to show incorrect time after a certain period of time

Recently, I encountered an issue with jquery flot while working on a real-time chart. Everything seemed to be functioning properly at first, but after some time had passed, I noticed a significant problem. Initially, the chart was updating correctly; howe ...

Executing Javascript dynamically in VueJS: Learn how to run code from a string efficiently

Currently, I am developing a website with VueJS that enables selected users to upload scripts for automatic execution upon page load. For instance, here is an example of the type of script a user may input: <script src="https://cdnjs.cloudflare.com/aja ...

Steps for leveraging pdfMake with live data

Recently delving into Angular, I've been exploring the capabilities of pdfMake. While I successfully incorporated static data, I'm facing challenges when attempting to utilize dynamic data. Any guidance on how to achieve this would be greatly app ...

Displayed unfamiliar Obj characters on Google Chrome

Hey there, I'm new to Vue JS and Vuetify and could really use some help! I've been trying to display some HTML content from my data using v-html in Vue JS, but for some reason, strange OBJ symbols keep showing up. Here is a screenshot of what I ...