Express 4.13.4 appears to be disregarding the cookie's expiration date when the moment.toDate() function is used

I've been encountering an issue where I am attempting to set a cookie with a specific expiry date of 3 months, but the expiration is not setting correctly.

Using momentJS, I created a date object for the desired time. The console confirms that the correct time is displayed, however, the cookie does not expire after 3 months as intended - instead, it expires in just a couple of minutes.

// Establish the date the cookies will expire on
var cookieDate = moment().add(6, 'months').toDate();
console.log(cookieDate);
res.cookie('username', user.username, { expires: cookieDate });

After reviewing the documentation, it simply states that a Date object should be passed in.

Browsing through stackoverflow, I found one suggestion here advising the use of req.session.cookie, which seems incorrect as cookies should be set for the client's response rather than in a session.

Answer №1

After experimenting a bit, I discovered that the Date object generated by moment.toDate() was technically correct but not compatible with Express.

To resolve the issue, I implemented the following code:

var expiryDate = new Date(moment().add(6, 'months').toDate());
res.cookie('username', user.username, { expires: expiryDate });

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

I must first log a variable using console.log, then execute a function on the same line, followed by logging the variable again

Essentially, I have a variable called c1 that is assigned a random hexadecimal value. After printing this to the console, I want to print another hex value without creating a new variable (because I'm feeling lazy). Instead, I intend to achieve this t ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

The variable in the dataTables JavaScript is not receiving the latest updates

//update function $('#dataTable tbody').on('click', '.am-text-secondary', function() { //extract id from selected row var rowData = table.row($(this).parents('tr')).data(); var updateId = rowData.id; ...

Display the picture for a few moments, then conceal it. A button will appear to reveal the following image after a short period

For my project, I want to create a webpage for school where I display one image that disappears after 5 seconds, followed by a button. The user must click the button before the next image appears and stays for another 5 seconds. This sequence repeats each ...

Implementing closure within a recursive function allows for better control

One of my functions is designed to take a parameter and print the last number in the Fibonacci Series. For example, if the parameter is 3, it would return 2 as the series progresses like 1, 1, 2. function recursionFib(num){ if(num ...

Enhancing communication with Socket.IO's private messaging feature

It feels like I have asked this question countless times already, but none of the answers seem to satisfy me. So, here I am trying once again, being as clear as possible. I am setting up a fresh Express project using the usual terminal commands: user$ ex ...

Extracting Data from JSON Structures

I am struggling with extracting data from a JSON string that looks like this: var txt= '{“group”: [ {“family1”: { “firstname”:”child1”, “secondname”:”chlid2” }}, {“family2”: { ...

Why do style assignments lose their motion when executed right after being made?

If you take a look at this specific fiddle in Webkit, you will see exactly what I am referring to. Is there a way to define the style of an element when it is first specified, and then its final state? I would like to be able to fully define a single-ste ...

`The value of an element within an array changes automatically`

In my current setup, I have a traditional array where each element represents an HTML element. The issue arises when I manipulate these elements within the array; any changes made to the HTML element also reflect in the array automatically. However, I pref ...

Display a Bootstrap input button group addon, where the first button has rounded corners only after the second button has been hidden

I am working on a button group and need to hide the second button dynamically. However, I am facing an issue where the first button has a 90° border. How can I adjust the code below to display button 1 with a rounded border? If I decide to hide "button ...

What are the capabilities of Ajax when it comes to utilizing select controls in J

Is there a way to trigger an ajax call when a select control value is clicked? The onChange event doesn't seem to work for me in this case :( This is what I have tried so far: JAVASCRIPT: <script> function swapContent(cv) { $("#myDiv"). ...

What is the best way to conduct tests on React components' methods and ensure they are integrated into my Istanbul coverage report

Is there a way to test the methods of react components and include them in my Istanbul test coverage? Edit: I'm using enzyme. Just wanted to mention that. Take, for instance, this component: class SearchFormContainer extends Component { static h ...

Issue encountered: Unforeseen command: POST karma

Whenever I try to run my test cases, I encounter the following error message: Error: Unexpected request: POST data/json/api.json it("should $watch value", function(){ var request = '/data/json/api.json'; $httpBackend.expectPOST(reque ...

What is the reason behind the browser not reusing the authorization headers following an authenticated XMLHttpRequest?

As I work on developing a Single Page Application using Angular, I have encountered an interesting challenge. The backend system exposes REST services that require Basic authentication. Surprisingly, while obtaining index.html or any of the scripts does no ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

Adjust the language code in a URL using JavaScript or Node.js

Within my common header file, there is a navbar that includes a multilanguage dropdown menu. The issue I am facing is that when I select a language from the dropdown, the page translates correctly. However, when I navigate to other pages, the selected lang ...

The "@aws-amplify/cli" does not support platforms with the type "Windows_NT" and architecture "ia32"

For my initial AWS project, I decided to use the amplify cli. After running npm i -g @aws-amplify/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcbfb0b59ce8f2eee8">[email protected]</a> and successfully configu ...

JavaScript's version of "a certain phrase within a text"

If I'm working in Python and need to verify if a certain value is present in a string, I would use: if "bar" in someString: ... What would be the equivalent code in Javascript for this task? ...

Issue with smart table sorting functionality

I've been working on a table with just one column that is populated from a string array. However, I'm struggling to get the sorting functionality to work properly. Can anyone pinpoint what mistake I might be making here? Steps taken so far: 1) ...

Tips for transmitting data from the server to the client side

From the code posted below, I am attempting to transfer the value access_token from the method fetchAuthenticationToken to the method fetch in Ws.js. In fetchAuthenticationToken, I receive the value for the access_token and then assign that value to both r ...