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

File download is initiated through an Ajax response

Utilizing Polymer's iron-ajax element, I am making an XMLHTTPRequest to a server endpoint: <iron-ajax id="ajax" method="POST" url="/export/" params='' handle-as="json" on-response="handleResponse" </iron-ajax> The resp ...

Can you clarify the purpose of response.on('data', function(data) {}); in this context?

I am curious about the inner workings of response.on("data"). After making a request to a web server, I receive a response. Following that, I utilize response.on("data" ...); and obtain some form of data. I am eager to uncover what kind of data is being p ...

Disabling ESLint errors is not possible within a React environment

I encountered an eslint error while attempting to commit the branch 147:14 error Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions I'm struggling to identify the issue in the code, even ...

Acquire key for object generated post push operation (using Angular with Firebase)

I'm running into some difficulties grasping the ins and outs of utilizing Firebase. I crafted a function to upload some data into my firebase database. My main concern is obtaining the Key that is generated after I successfully push the data into the ...

Angular is unable to POST to Rails server with the content-type set as application/json

Currently, I am attempting to send a POST request with Content-Type: application/json from Angular to my Rails backend. However, an error is being displayed in the console: angular.js:12578 OPTIONS http://localhost:3000/api/student_create 404 (Not Found ...

Activating a tab using a JS call in Bootstrap with the data-toggle attribute

My JSP page is using bootstrap's data-toggle="tab" functionality to display tabs. When the page loads, one tab is made active by default. <ul class="nav st-nav-tabs"> <li class="active"><a href="#tab1" data-toggle="tab">First Ta ...

Unable to convert the BSON type to a Date in MongoDB

I am currently facing an issue while attempting to filter data stored in MongoDB utilizing parameters from the URL. Whenever I send the request, the server crashes and displays the error message: can't convert from BSON type string to Date I attemp ...

problem with the visibility of elements in my HTML CSS project

How do I prevent background images from showing when hovering over squares to reveal visible images using CSS? h1 { text-align: center; } .floating-box { float: left; border: 1px solid black; width: 300px; height: 300px; margin: 0px; } div ...

Encountering issues with styling the search bar using CSS and unable to see any changes reflected

I am currently working on creating a searchBar and customizing its CSS, but unfortunately, most of the styling properties seem to not be taking effect. So far, only changing colors seems to work as expected. .mainBar{ background-color: blue; width: ...

Transferring user-selected values from JavaScript to a PHP file

When sending values from JavaScript to a PHP file, everything works smoothly when all the values are collected. Step1 functions perfectly as both fields are mandatory. However, in Step2, values are only sent when all the fields are selected. There are co ...

Elevating the Material Design Lite Progress bar using ReactJS

I currently have MDL running with React and it appears to be functioning properly. The Progress Bar is displaying on the page as expected, loading with the specified progress on page load when a number is entered directly: document.querySelector('#qu ...

Is there a way to incorporate CSS into an element utilizing jQuery when only a class is available for identification, and when the time in the innerHTML is within a 5-minute range from the current time?

I have some HTML code that I need help with: <td class="mw-enhanced-rc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;18:10&nbsp;</td> My goal is to use JavaScript to make the time bold. $('td[class^="mw-enhanced-rc"]').eac ...

Ways for enabling the user to choose the layout option

I am looking to develop a customized reporting system where users can select the specific fields they want to include in the report as well as arrange the layout of these fields. The data for the reports is sourced from a CSV file with numerous columns. Us ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...

Can you explain the distinction between key and id in a React component?

I have included this code snippet in the parent component. <RefreshSelect isMulti cacheOptions id='a' key = 'a' components={makeAnimated()} options={th ...

Refresh in AJAX, automated loading for seamless transition to a different page

Having an issue with the page not auto-refreshing, although it loads when I manually refresh. P.S Loading the page onto another page. Below is my HTML and AJAX code along with its database: The Trigger Button <?php $data = mysqli_query ...

Incorporating Blank Class into HTML Tag with Modernizr

Currently, I am experimenting with Modernizr for the first time and facing some challenges in adding a class to the HTML tag as per the documentation. To check compatibility for the CSS Object Fit property, I used Modernizr's build feature to create ...

How to bypass CORS restrictions in XMLHttpRequest by manipulating HTTP headers?

Currently experimenting with the (deprecated) Twitter API 1.0 For instance, I am interested in retrieving data from the API utilizing AJAX browser requests on cross-origin web pages. This could be a new tab, a local HTML file, or any established website. ...

What is the best way to apply a specific style based on the book ID or card ID when a click event occurs on a specific card in vue.js

My latest project involves creating a page that displays a variety of books, with the data being fetched from a backend API and presented as cards. Each book card features two button sections: the first section includes "ADD TO BAG" and "WISHLIST" buttons ...

Is there a way to incorporate arguments into my discord.js commands?

Hey there! I'm looking to enhance my Discord commands by adding arguments, such as !ban {username}. Any tips or guidance on the best approach for this would be amazing! const Bot = new Discord.Bot({ intents: ["GUILD_MESSAGES", "GUIL ...