What steps should I take to ensure that a cookie has been properly set before utilizing it?

I'm in the process of developing a JWT authorization code flow using Next.js and NestJS.

Below is the POST request being sent from the frontend to the backend server:

const response = await fetch(
  'http://localhost:4000/auth/42/callback?code=' + code, { // The code parameter is received from the OAuth server
    method: 'POST',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  }
);

Once the backend receives this request, it processes it by generating a JWT and sending it back to the frontend via the response.

@Post('42/callback')
async Callback(@Query('code') code: string, @Res({passthrough: true}) res) {
  if (!code) {
    res.status(400).send('Missing code');
    return;
  }

  try {
    const response = await this.authService.exchangeCodeForToken(code);
    const jwt = await this.authService.handleCallback(response);
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.cookie('jwt', jwt, {
      sameSite: 'strict'
    });
    res.status(200).send();
  } catch (error) {
    console.error(error);
    res.status(500).send('Internal server error');
  }
}

Although the browser successfully sets the jwt cookie, there seems to be a delay in its availability for immediate use.

import jwtDecode from 'jwt-decode';
import { useCookies } from 'react-cookie';

const [ cookies ] = useCookies();

const jwt = cookies.jwt;
const jwtPayload: any = jwtDecode(jwt); // At this point, jwt is returning as undefined

I've inspected the Network Profiler in the browser but haven't been able to identify any noticeable latency issues. https://i.stack.imgur.com/pEGRV.png

Answer №1

After much searching, I have finally discovered a solution to my dilemma. It seems that the react-cookie package can be unreliable in certain scenarios (check out this issue or this one). The useCookies hook does not update when a new cookie is added. Until this issue is resolved, the recommended workaround is to utilize universal-cookie instead.

Below is an example implementation:

import Cookies from 'universal-cookie';
import jwtDecode from 'jwt-decode';

const cookies = new Cookies();
const jwt = cookies.get('jwt');
const decodedPayload = jwtDecode(jwt);

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

Encountering a compilation error while compiling using Angular Ivy

Encountering a compile time error in my Angular 8 project when enabling angular Ivy. Upgrading to version 8.1.0 did not solve the issue, and I continue to receive the following error: D:\Users\Backup>ng build shared Building Angular Package B ...

Issue with hydration when utilizing next-usequerystate in Next.js

I'm currently testing out a basic example that I found on the npm page for next-usequerystate. Take a look at the code snippet below: import { useQueryState } from 'next-usequerystate' export default () => { const [name, setName] = us ...

State does not contain the specified property - Navigating with React Router Hooks in TypeScript

I've been experiencing issues when using react-router-dom hooks with TypeScript. Whenever I try to access a state property, I get an error stating that it doesn't exist. For more information, you can visit: To continue development, one workaro ...

When using .map() to iterate through an array of objects in Next.js, why does the data display in the console but

I'm facing an issue with displaying the elements of an array in HTML. I'm fetching data from the Bscscan API and while I can retrieve data successfully from the first API, the second one doesn't display the data in the local browser. I' ...

Declaring module public type definitions for NPM in Typescript: A comprehensive guide

I have recently developed a npm package called observe-object-path, which can be found on GitHub at https://github.com/d6u/observe-object-path. This package is written in Typescript and has a build step that compiles it down to ES5 for compatibility with ...

Is there a way for me to update the value and then store it in a file?

I am currently developing a compact admin panel I have a file named settings.ini which contains the following data: siteName=Site name sideDesc= Site Description Can anyone guide me on how to retrieve this data for the admin panel, update its value, and t ...

Creating a time-limited personal link with Django Rest Framework and React

I have a frontend application built with React Framework that I want to provide access to via a time-limited personal link, without the need for additional authentication functions. With approximately 1-2 new users per day, my proposed implementation is as ...

Delivery person receiving biscuit but my internet browser doesn't seem to be getting it when I attempt to retrieve it

Currently, I am in the process of creating a website using Flask and React. The user is required to input an email and password on a form, which is then sent via axios.post to the backend. The backend checks if the email and password match with the databas ...

Navigating through challenges with zoom and api call errors

When attempting to create a jwt and call the Zoom API, I encountered an error {'code': 124, 'message': 'Invalid access token.'}. What does this message signify? ApiKey = 'xxx' ApiSercret = 'xxx' mail = requ ...

Error retrieving data: The JSON response was invalid, as an unexpected token `<` was found at the beginning of the response. This issue occurred while using

Utilizing the getStaticProps and getStaticPaths functions, I made a fetch API call to an API endpoint (specifically a Wordpress headless CMS) in order to set dynamic routing paths. While running npm dev, everything functions correctly as the data is succes ...

Address aliases in the webpack configuration file

When utilizing webpack, it is possible to write the configuration file using TypeScript. However, it is crucial to ensure that any alias paths present in the config file are resolved to their mapped paths. It should be noted that this pertains specificall ...

Encountering error "module fibers/future not found" while creating a meteor method in typescript

While working on a Meteor method for async function in my project that combines Meteor with Angular2 using Typescript ES6, I encountered an error. The issue is related to a sync problem in the insert query when inserting data with the same name. To resolve ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...

Error encountered in Angular NGRX while accessing the store: Trying to read property 'map' of an undefined variable

I have integrated NGRX effects into my Angular application and encountered the following error. I'm uncertain if I am using the selector correctly in my component to query the store? core.js:6162 ERROR TypeError: Cannot read property 'map' o ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

Inheritance of Type Member in TypeScript

My data structure looks like this: export abstract class Person { ... } export class FPerson extends Person { a: A; b: B; } export class JPerson extends Person { c: C; } export class User { person: Person; } When dealing with the s ...

Using Higher Order Components in React with TypeScript to pass a component as a prop

Exploring the steps outlined in this guide: https://reacttraining.com/react-router/web/example/auth-workflow. Attempting to replicate the code: const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props = ...

Creating a React component that allows for pagination using data fetched from a

I have a Spring Boot endpoint that retrieves and lists items from a database: @RequestMapping(method = RequestMethod.GET, value = "/task", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> processTask(@Valid TaskSearchP ...

Integrating Form Submission with Mailchimp API in Next.js

After creating a form to collect user input data and send it to the Mailchimp audience list using their API, I encountered an issue. The problem is that when the form is submitted with both the user's firstname and email inputs, only the email input i ...

I need help with obtaining the director's name and their image from Supabase. Can anyone assist

Table: Director (id, director_name, director_image) Table: movies (id, movie_name, movie_description) Table: movie_director (director_id, movie_id) // Foreign keys: movie_id and director_id const { data, error } = await supabase .from(&a ...