Create a cookie on a subdomain that is accessible by all other subdomains

I have been working on a NextJS project that involves multiple apps on separate subdomains. My objective is to enable single sign-on so that when I log in to one app, I am automatically signed in to all the others. We are utilizing nookies as our cookie handler and creating a cookie with a JWT token payload received from an API. Despite trying to manually set the cookie domain, it did not result in the cookie being set on the main domain as expected.

Here are the steps I have taken:

setCookie(
    null,
    "token",
    `JWT ${data.tokenAuth.token}`,
    {
        maxAge: 29 * 24 * 60 * 60,
        path: "/",
        domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
    }
);

I attempted setting NEXT_PUBLIC_COOKIE_DOMAIN to both "example.com" and ".example.com", but neither approach successfully set the cookie on the main domain; it was always assigned to the current subdomain instead. I also considered placing the login page under "example.com/login" to see if this would help set the cookie on the main domain for universal access, but I prefer finding a solution without resorting to this method. Having reviewed RFC 6265, my understanding is that setting cookies only works from the main domain, yet the tracking mechanism we are using somehow manages to assign “.example.com” for its cookies. What could I be overlooking? Thank you in advance for any insights provided.

Answer №1

For effective cross-subdomain cookie sharing, it is important to ensure that cookies are shared across subdomains by setting the domain attribute with a leading dot (e.g., ".example.com"). It is recommended to avoid using SameSite: Strict for cross-site requests and instead consider using None with caution. Secure cookies play a vital role in HTTPS sites, so make sure to set the path attribute to "/" for domain-wide access. Verify that the environment variable NEXT_PUBLIC_COOKIE_DOMAIN is configured correctly and test your setup using browser tools to confirm the correct domain and attributes of the cookie.

If you are looking for an example on how to set a cookie using nookies, here is a sample code snippet:

import { setCookie } from "nookies";

// Set cookie with domain and other attributes
setCookie(null, "token", `JWT ${data.tokenAuth.token}`, {
  maxAge: 29 * 24 * 60 * 60, // 29 days
  path: "/",
  domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN, // Should be ".example.com"
  secure: true, // Set to true if served over HTTPS
  sameSite: "None", // If necessary for your use case
});

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

tips on displaying textbox content on a php webpage

I have a piece of code where, when text is entered into a textbox and the add attribute button is clicked, the entered value is displayed on the page twice. One appears in the first row of a table, and the other appears in the first row of a second table. ...

Fill the next Thursday with JavaScript

I'm having trouble updating the date for the upcoming Thursday using JavaScript. The current script works fine until the end of the month, but if it's the 25th of August, the output will be "Next Thursday - 8/32/2022". I need a more intelligent s ...

Encountering a browser error while running the production build in Next.js

Encountering a browser error when attempting to run a production build using Next.js react_devtools_backend.js:4049 TypeError: Cannot set property 'length' of undefined at c (_app-eb48c4090f186b688116.js:1) at 5513.89ba65240e9cb87cd0f5. ...

What is the best way to send HTML tag content to mark.js and delimit them with a space or comma?

I have been utilizing the mark.js library to highlight keywords on a webpage, and it's been working well. However, I now need to insert an extra space or a comma after each tag such as h1, h2, etc. Initially, I thought about using a loop like the one ...

Changing Background Color on Div Click

After spending a considerable amount of time on this, I find myself getting confused and stuck. It seems like I might be overlooking something crucial. Essentially, my code is designed to have the default div background (gamebg), and upon clicking one of t ...

Can you explain the significance of the "@" symbol prefix found in npm package names?

While reading through the Angular Component Router documentation, I came across an npm command that caught my attention: npm install @angular/router --save I'm puzzled by the meaning of @angular/router. Is this entire string a package name? If so, ...

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...

Assistance with the Chakra UI Range Slider in React

I could use some help figuring out where exactly to implement my OnChange and Map functions for mapping JSON data into a Range Slider. Everything seems to be rendering correctly, but I keep encountering an error when I try to move the slider: Unhandled Ru ...

I am currently exploring React Router, but I am struggling to grasp this particular behavior

My Express server serves the Create-React-App build. When I access http://localhost:8000/ while the server is listening, my page loads correctly. However, if I reload the page or navigate directly to it from the navigation bar, instead of seeing the UI, pl ...

Error in Node.js: Trying to access property 'get' of an undefined object

Although I have some knowledge of JavaScript, I am new to Node.js. Despite it being a common issue, I am having trouble identifying the source of the error because my debugging skills in Node.js are lacking. Here is my app.js: var index = require('. ...

Save the retrieved data in a variable and pass the entire JSON object as a prop to a React component

Having some trouble with my code. I need the app to fetch a JSON from an API and pass it as a prop so that each component file can use it and display the element on the screen. The issue is, I can't seem to figure out how to store the fetched informa ...

I am interested in checking the dates of the current date and disabling the button if the date falls within that range

I am attempting to deactivate a button if the current date falls within a three-month period. Despite my efforts to use a combination of Php and JavaScript, I was unable to make it work. PHP Code @php($found = false) @foreach($doctors as $doctor) ...

Tips for Redirecting to a Different Page in Next.js Using CSS Media Queries

Hey there, I am completely new to utilizing Next.js and currently facing an interesting scenario. My goal is to redirect the user to the route /messages if they input the route /messages/123. This redirection will be based on a CSS media query - meaning th ...

What is the best way to choose a single item from an array using jQuery?

Within an array, I have IDs and descriptions like: var tablica = [{"3":"asdasd asd"},{"19":"asddas fff"},{"111111":"adas asf asdff ff"},{"4":"re"},{"5":"asdasd"},{"6":"we"},{"7":"asdasdgg"},{"9":"asdasdasd"},{"16":"sdads"},{"10":"asdgg"},{"11":"ggg"}]; ...

Is the state of the React.js component empty?

HTML: <!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> ...

Developing a pop-up feature that triggers upon clicking for a miniature rich text editing

Looking to integrate the Tiny rich text editor into my code. Check out the TextEditor.js component below: import React from 'react'; import { Editor } from '@tinymce/tinymce-react'; class App extends React.Component { handleEditorCha ...

Toggle the visibility of a table column based on user selection in Vue.js

I am having issues with displaying and hiding based on checkbox click events. Can anyone assist in identifying the mistake? When clicking on an ID, it should hide the ID column. Similarly, clicking on "first" should show/hide based on checkbox clicks, and ...

I am having trouble resolving 'otp-input-react' in my project directory at D:projectappsrc

I have been troubleshooting this issue but haven't been able to find a solution yet. I even tried uninstalling and reinstalling the package, but it still isn't working as expected. Here are some images for better clarity: https://i.stack.imgur.c ...

Solving problems with accessing global variables in React Redux

I'm currently working on implementing a global state in react-redux for my project. However, I've encountered an issue with retrieving updated values after dispatching an action to populate the global state for the User. Below are snippets of the ...

What distinguishes running rm -rf node_modules + npm i from using npm ci?

When using a Unix system and needing to clean out the node modules folder, is there any benefit or distinction between executing rm -rf node_modules followed by npm i as opposed to npm ci My understanding is that both yield the same outcome, but is th ...