When using Next.js getServerSideProps(), cookies are not accessible on the initial render after a redirect, but they become available upon refreshing the page

Within my Next.js application, I am serving cookies from the server-side API like this:

res.setHeader('Set-Cookie', AJWT)
res.redirect(302, '/')

Now, in my index.js file, I am attempting to retrieve the cookie before the page is rendered:

export async function getServerSideProps(context) {
    let cookies = context.req.headers.cookie

    if (typeof cookies !== 'string') {
        return {
            props: { auth: false },
        }
    } else {
        const { AJWT } = cookie.parse(cookies)

        return {
            props: { auth: AJWT ? true : false },
        }
    }
}

After the initial redirect, the first render does not have access to the cookies. However, upon refreshing, they are successfully captured. Is there a way to ensure that the cookies are available on the very first render?

UPDATE: It should be noted that the cookie is indeed visible in my devtools when I am initially redirected.

Answer №1

Check out where the cookie is pointing to. I encountered a similar issue when my cookies were only set for one specific page.

setCookie(undefined, 'jumpy', accessToken, {
  maxAge: 60 * 60 * 1, // 60 minutes
  path: '/',
})

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

Error: The DOM is throwing an uncaught TypeError because it cannot read the property 'children' of an undefined value

After delving into the depths of the DOM, I zeroed in on a specific element that I was eager to access. To reach this elusive element, I meticulously navigated through the DOM using the following code snippet: var body = document.body; var bodych ...

Designate a Cookie for individual users

Currently, I am in the process of building a straightforward Wordpress website that aims to monitor a user's order using a specific Cookie. Although most of the functionalities are already implemented, an unexpected issue has surfaced. Upon logging i ...

Displaying a dynamic progress bar across all elements in fullscreen mode

I am looking to implement a full-screen indeterminate progress bar that overlays all screen elements. Here is my specific use case: When a user fills out a form, including an email field, the email id is checked against a database via ajax. While waiting ...

What could possibly be causing the "Unexpected token (" error to appear in this code?

Sorry if this appears as a typo that I am struggling to identify. My browser (Chrome) is highlighting the following line <a class="carousel-link" onclick="function(){jQuery('#coffee-modal').modal('show');}">Book a coffee</a> ...

how to share global variables across all components in react js

Operating a shopping cart website requires transmitting values to all components. For instance, when a user logs into the site, I save their information in localStorage. Now, most components need access to this data. My dilemma is whether I should retriev ...

Having a problem with file uploads in node.js using multer. The variables req.file and req.files are always coming

I am encountering an issue with uploading a file to my server, as both req.file and req.files are consistently undefined on my POST REST endpoint. The file I'm attempting to upload is a ".dat" file, and my expectation is to receive a JSON response. ...

Using async/await in React to retrieve data after a form submission

I am currently facing an issue with displaying data fetched from an API on the screen. My goal is to retrieve data when a user types something in a form and clicks the submit button. The error message I am encountering is: TypeError: Cannot read propert ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

Utilizing JavaScript as an alternative to PHP in this specific scenario

Hey everyone, I'm looking to pass data from PHP to JavaScript. Below is my PHP code that I need to adapt for use in JavaScript: $result = dbMySql::Exec('SELECT Latitude,Longitude FROM data'); while ($row = mysqli_fetch_assoc($result)) $ ...

Is it possible to load a JavaScript file from a different domain using a bookmarklet?

I'm a newcomer to bookmarklets and I am experimenting with loading a JavaScript file from my own server/domain using the following bookmarklet/javascript code: javascript:(function(){s=document.createElement('script'); s.type=' ...

Establishing a database environment for Firebase with Next.js on Vercel for both production and development purposes

Our database is powered by Firestore and we utilize Vercel's Next.js hosting platform. To maintain completely separate development and production databases, we created two distinct projects on Firebase, resulting in unique API keys for each project. ...

Stripping quotation marks from CSV information using Javascript

After performing a fetch request using JavaScript, I have converted JSON data into CSV format. datetime","open","high","low","close","volume" "2020-01-28","312.48999","318.39999","312.19000","317.69000","31027981" "2020-01-27","309.89999","311.76001","30 ...

Prevent multiple requests on jQuery infinite scrolling

I have implemented pagination on my website where the next page is loaded automatically when the user reaches the bottom of the page. This is achieved by using jQuery's .on('scroll', this.detectScroll()) method which triggers a function to l ...

Vue dynamic components fail to re-render within a v-for loop upon data changes

I've created a dynamic table component that allows me to modify columns by changing their ordering, adding new ones, or removing existing ones. The structure of my table body is as follows: <tr v-for="row in data" :key="row.id"& ...

Encountering NaN while trying to retrieve the duration in JavaScript

I'm having an issue retrieving the duration of an mp4 video file when the HTML document loads. Here's my code: (function ($, root, undefined) { $(function () { 'use strict'; $(document).ready(function() { ...

Button Triggering Javascript

Looking for a handy solution that allows users to either accept or reject a website's cookie policy. I came across an interesting library called cookies-EU-Banner (found at ) which seems to be quite popular. It recognizes when the user clicks on Reje ...

Attempting to remove options in a Multiple Choice scenario by selecting the X icon beside each one

I'm working on a multiple choice quiz and I'd like to add a button or icon resembling X in front of each option (even in front of the radio button), so that when I click on it, only that specific option is deleted. How can I achieve this? For in ...

Is it possible to dynamically add plotLines to the xAxis using datetime in HighCharts?

Hey there! I've been playing around with adding plotlines in Highcharts and I'm loving it. It's really easy to define a date time on the xAxis for a plotline, like this: xAxis: { plotLines: [{ color: '#dadada', ...

Debugging Slideshows Using JavaScript

I am currently working on creating a slideshow and I'm facing some challenges with the JavaScript functionality. Everything seems to be running smoothly except for one issue - when I click right once, it transitions correctly, but if I then click left ...

When viewing the material-ui Chip component at normal zoom, a border outlines the element, but this border disappears when zoomed in or out, regardless of

Edit I have recently discovered a solution to the unusual problem I was facing with the material-ui Chip Component. By adding the line -webkit-appearance: none; to the root div for the Chip, the issue seems to resolve itself. However, this line is being a ...