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

What is the best way to create a TypeScript function that merges actions together?

I am currently working on a TypeScript function similar to the following: import multipleActionObject from page; it("should be able to perform multiple operations", () => { multipleActionObject.chooseIndex(4).setValue(10); } Inste ...

What are the steps for integrating Socket.IO into NUXT 3?

I am in search of a solution to integrate Socket.IO with my Nuxt 3 application. My requirement is for the Nuxt app and the Socket.IO server to operate on the same port, and for the Socket.IO server to automatically initiate as soon as the Nuxt app is ready ...

What is the best way to retrieve the dataset object from a chart object using chart.js in typescript?

Currently, I am facing a challenge in creating a new custom plugin for chart.js. Specifically, I am encountering a type error while attempting to retrieve the dataset option from the chart object. Below is the code snippet of the plugin: const gaugeNeedle ...

Issues discovered with using Typescript in Visual Studio 2015

I'm having trouble figuring out the issue. Right now, the typescript file is not appearing correctly in Visual Studio 2015. Take a look at the image linked here: https://i.stack.imgur.com/oXXWD.png ...

Creating a Dynamic Table with Angular 6 - Automating the Population of Content Values

I have a task of populating a table with data from a JSON file. Take a look at the following code snippet: <table> <thead> <tr> <th *ngFor="let datakeys of listData[0] | keys">{{ datakeys }}</th> </tr> < ...

Store a video file on your device's memory

Currently, I am storing simple strings in local storage. However, I am now facing the issue of wanting to save videos and images to local storage. Due to the limitations of localStorage supporting only strings, I am unsure of how to achieve this. If you h ...

The Array of Objects is not being generated from Action and Effects

I'm attempting to retrieve an array of objects stored in the User model. I've created both an Action and an Effect for this purpose. The structure of the User Model is as follows: export interface User { _id: string, firstName: string, lastName: ...

What is the best way to create a generic function parameter for a single property of an object?

I am trying to refactor a generic function into accepting parameters as a single object function test<T>(a: string, b: T, c: number) Instead, I want the function to receive an object like this: function test(params: {a: string; b: T, c: number}) I ...

Encountering Angular Material UI issues following the transition from version 11 to 12

I am currently in the process of updating my Angular application from version 11 to 12, integrating Angular Material, and encountering some error messages: Error No.1 - Error NG8002: Cannot bind to 'ngModel' as it is not a recognized property of ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...

Redis-om and Next.js - Resolving Entity Problems

Currently, I am exploring search functionality with Redis (redis-om) in the new NextJS 13 environment within the app directory. As I follow this tutorial, I encounter an error related to Entity. I'm unsure if this is a bug or if I've made a mista ...

Adjusting the Material UI Select handleChange function

const handleObjectChange = (event: React.ChangeEvent<{ value: unknown }>) => { const { options } = event.target as HTMLSelectElement; const selectedValues: object[] = []; for (let i = 0, l = options.length; i < l; i += 1) { if ...

Obtaining attribute data value upon selection change in Angular 4

Having trouble retrieving the value from data-somedata in my code... <select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (change)="menuChange($event)"> <option *ngFor="let menu_optional of menu_optionals" value= ...

Encountering an error message of "BrowserAuthError:uninitialized_public_client_application" while attempting to use SSO with MSAL in a React and Next.js

I am currently developing a React application using Next.js 14 and the App router. I am attempting to implement single sign-on (SSO) using Azure Msal. In my project, I have created a Msal.ts file which contains the MSAL configuration that I am utilizing i ...

Can TypeScript Implement a Dictionary Feature Similar to C#?

Looking for guidance on how to use TypeScript interface to define these C# models: public class PageModel { public long Id { get; set; } public string Name { get; set; } public IDictionary<string, FieldModel> Fields { get; set; } } pu ...

Utilizing OctoKit and Auth0 for Github authentication within a NextJS environment

Currently, I am in the process of developing a Next JS application that incorporates Github Login via Auth0 and utilizes Octokit to retrieve user information and repositories. To obtain the IDP, I needed to configure a management api within Auth0. This li ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Encountered a 401 error with NextJS and the "openai api" when calling the createChatCompletion() endpoint, but received a 200 ok response when calling create

A Short Summary When using NextJS api router, the call to openai api endpoint createChatCompletion() failed. However, it was successful when done with pure Node.js code. More Details I attempted to use NextJS's api router as demonstrated here for ca ...

What could be causing the global npm package to not be utilized for module dependencies?

My typescript and ts-node are already installed globally. In my package.json file, I have the necessary configurations to run tests with npm test. Everything works fine since ts-node and typescript are installed as local modules. { "name": "two_sum", ...

Adding negative values to the Tailwind CSS utility plugin is a simple process that can greatly enhance

Adding Negative Values to Tailwind CSS Utility Plugin Quick Summary: I've developed a custom Tailwind utility plugin that includes numeric values. I'm looking for a way to introduce negative numbers by adding a - at the start of the class, simi ...