Utilizing server-side cookies in next.js and nest.js for efficient data storage

I have been working on a small application using Next.js and Nest.js. One of the functionalities I implemented is a /login call in my client, which expects an HttpOnly Cookie from the server in response. Upon receiving a successful response, the user should be redirected to the homepage, where authentication is required. Although I can see the cookie in the network request's response headers, I'm unsure if I've missed something as the cookie is not present in the request headers in my middleware without manually setting it. Another potential issue I noticed is that after logging in, I can view the cookie using document.cookie in the browser console.

Server:

  @Public()
  @HttpCode(HttpStatus.OK)
  @Post('signIn')
  async signIn(@Body() signInDto: SignInDto, @Res() response: Response) {
    const { access_token, role } = await this.authService.signIn(
      signInDto.username,
      signInDto.password,
    );
    response.cookie('jwt', access_token, {
      sameSite: 'lax',
      path: '/',
      secure: false,
      httpOnly: true,
    });
    response.send({ message: 'Authentication Successful', role });
  }

Client:

const LoginPage = () => {
  // should we move this out to an api folder?
  async function handleSubmit(e: FormData) {
    "use server";

    // const formData = new FormData(e.get);
    const username = e.get("username");
    const password = e.get("password");

    const response = await fetch("http://localhost:8080/auth/signIn", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ username, password }),
    });
    console.log("response in cookie ", response.headers.get("Set-Cookie"));
// without this I cannot see the cookie in the browser nor can I make the call on my homepage
    const setCookieHeader = response.headers.get("Set-Cookie");
    if (setCookieHeader) {
      const jwtToken = setCookieHeader.split(";")[0].split("=")[1];
      console.log("JWT Token:", jwtToken);
      cookies().set({ name: "jwt", value: jwtToken, secure: true, path: "/" });
    }

    // if (!response.ok) doesn't work investigate
    if (!response.ok) {
      console.log("Invalid username or password");
      // how can we display an error here without state?
      return;
    }

    // redirect to homepage on success
    redirect("/");
  }

Answer №1

When working with NestJS, you can set a cookie using the following code snippet: response.setHeader('Set-Cookie', accessToken);

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

Incorporate a background image property using Jquery

Can anyone help me with adding the css background-image:url("xxxxx") property to my code? jQuery('#'+$trackID+' .sc_thumb').attr('src',$thumb_url); jQuery('#'+$trackID+' .sc_container').css('display& ...

Is there a way to retrieve a JSON result from an API call using jQuery (or plain JavaScript) without relying on Ajax?

As someone new to JS and jQuery, I am working on building a key-value map from an API call that returns an array of key-value pairs. [{"key":"191","value":244}, ... , {"key":"920","value":130}] I have created the following ajax code in my attempt to achi ...

npm fails during the build process due to webpack issues

I find myself lost in trying to pinpoint the right question to ask, but I am encountering a failure while running npm run build. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395a5655564b14564b5e585750435c4b790817091709" ...

Exploring how to use React with a select component featuring objects

Hello, I am new to working with React and I have a question regarding the select component of Material UI. Here's my situation: I am creating functionality for creating and editing a User object. This User object has a primary key and some data, incl ...

Tips for implementing pagination on a large JSON file without traditional pagination controls

Looking for the best way to implement pagination in a NextJs app that loads products from a local JSON file? This JSON file doesn't have any page properties, so the only option is to limit the number of products shown by using slice: {Object ...

Obtaining the date for the previous month using JavaScript or jQuery

I need to retrieve a specific date in JavaScript. My goal is to obtain the current date based on a variable named frequency, which can have values of Daily, Weekly, or Monthly. if(frequency=="daily") { date='current_date -2 days'; } e ...

Guide on transforming a PHP array encoded in JSON into a JavaScript array

After fetching a JSON encoded array via AJAX from a PHP file, I need to manipulate it as an array in JavaScript. How can I achieve this? Here is my AJAX call to the PHP File: $.ajax({ type:"POST", url:"ajaxfetch.php", success:function(re ...

What is the most efficient way to handle dependencies and instantiate objects just once in JavaScript?

I am interested in discovering reliable and tested design patterns in Javascript that ensure the loading of dependencies only once, as well as instantiating an object only once within the DOM. Specifically, I have the following scenario: // Block A in th ...

Performing a dynamic animation by toggling the class of an element with "classList.toggle" in JavaScript

I have been attempting to incorporate a fade animation using CSS when altering the class of the input and label elements within a form by utilizing the classList.toggle method in JavaScript. I'm puzzled as to why my code isn't producing the desir ...

Ways to identify if the requested image is error-free (403 Forbidden)

One of my scripts loads an image from a specific source every 300 ms, but sometimes it receives a 403 Forbidden response. When this happens, the image element ends up blank. I want to find a way to verify if the image has received a valid 200 response befo ...

Is it feasible to access a variable outside the scope of a function if it is initially created within the scope of another function that returns a function using that same variable?

function creatPrintNumFunction() { var num= 12; return function printNum() { console.log(num); } } var printer = creatPrintNumFunction(); printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside t ...

Changing a date string to MM DD format in React without using plain JavaScript

I'm familiar with how to handle this outside of React. My issue is that I have a date string coming from an API within an object, and I need to reformat it. The current format is "2022-12-13T06:00Z" but I want it to display as "December 13". The objec ...

Generating a JavaScript array containing all elements belonging to a specific class name

As I work on my website, I am attempting to create an array from elements that have a specific class. This array should retrieve the videofile attribute value from all `a` tags with the class `videoLink`. The desired values in the final array should be: ...

Create a personalized form with HTML and JQuery

Currently, the data is displayed on a page in the following format: AB123 | LHRLAX | J9 I7 C9 D9 A6 | -0655 0910 -------------------------------------------------------- CF1153 | LHRLAX | I7 J7 Z9 T9 V7 | -0910 1305 ---------------- ...

Unable to retrieve the contents of a previous shopping cart

I need to update my shopping cart. I am trying to retrieve the information from my old cart, but for some reason, it's not working properly and I keep getting a quantity of 1. Below is the code for the app.post request: app.post("/add-to-cart/:i ...

What is the interaction between Parse Cloud Code and Parse Server like?

After reviewing Parse's documentation on Cloud Code, I find myself puzzled. They make it clear that Cloud Code is not running in a Node.js environment. What does this mean for the functionality of my server? Even though the server uses Node.js & Exp ...

Struggling to retrieve data from AJAX call

I'm having trouble accessing the data returned from a GET AJAX call. The call is successfully retrieving the data, but I am unable to store it in a variable and use it. Although I understand that AJAX calls are asynchronous, I have experimented with ...

The content is overflowing outside the boundaries of the div, yet there is no

I am currently utilizing jQuery to dynamically load the content of a text file into a div element. However, when the content exceeds the dimensions of the div, no scroll bar is displayed. Here is the HTML structure: <!DOCTYPE html> <html lang=" ...

Activate the Select List to Appear Only When a Search is Conducted

Currently, I have implemented the react-select API in order to provide language options for selection. <Select isMulti name="langs" options={langOptions} defaultValue={{ value: "English", label: "English", nativeNam ...

Leveraging IE conditional comments for including CSS or JavaScript files can lead to an increase in the number of HTTP

Our web designer has implemented special pages for Internet Explorer by using IE-specific comments. This means that certain stylesheets are only loaded if the user is using a specific version of IE: <!--[if lt IE 7]> <link type="text/css" rel="st ...