Redirecting with Express js when the cookie is not found

I successfully integrated Facebook login using Passport-js and also set up Cookie-strategy for traditional username/password login on my Express-js backend with a React front-end. The backend and frontend are hosted on separate servers and domains (backend-client.com, frontend-client.com).

While everything works smoothly on localhost, I encounter issues in the stage and production environment. Not sure if it's relevant, but I'm hosting my applications on Heroku.

The problem:

After completing Facebook authentication, the Express server redirects the user to the frontend app with a JWT cookie containing user information to verify their login status.

const cookieSettings = {
    domain: process.env.COOKIE_DOMAIN,
    secure : (process.env.APP_MODE === 'local' ? false  : true),
    httpOnly : true,
};

const cookieMaxAge = {
    maxAge : 14 * 24 * 60 * 60 * 1000 // 14 days, 24h, 60 min, 60 sec * miliseconds
}

router.get('/auth/facebook/', passport.authenticate('facebook'));
router.get('/auth/facebook/callback', function(req, res, next) {
    passport.authenticate('facebook', async function (err, profile, info) {
        if (err || !profile) {
            res.redirect(`${process.env.FRONTEND_BASE_URL}?success=0`);
        }
        const user = await User.findOne({ facebookId : profile.facebookId });
        return user.generateAuthToken().then((token) => {
            res.cookie(COOKIE_NAME, token.token, {...cookieSettings, ...cookieMaxAge});
            res.redirect(`${process.env.FRONTEND_BASE_URL}?success=1`); 
        });
    })(req, res, next);
});

Despite the presence of the cookie when hitting /auth/facebook/callback: https://i.stack.imgur.com/x2zjH.png

No cookie is sent in the response headers upon returning to the frontend client.

I'm struggling to understand why this happens. Could there be some fundamental misunderstanding about how cookies work?

https://i.stack.imgur.com/kLoAN.png

Side note: When users log in with their username and password, the cookie is successfully returned. This login method uses ajax requests with Axios without any issues related to cookie settings.

Answer №1

After about a week, I discovered that the root cause of the problem was related to a domain issue on Heroku. I had been using two separate Heroku domains for my frontend and backend applications (backend.herokuapp.com, frontend.herokuapp.com).

As stated in the Heroku documentation

To clarify, certain browsers prevent applications within the herokuapp.com domain from setting cookies for *.herokuapp.com.

To resolve this issue, I decided to add custom domains to both my backend (backend.mycustomdomain.com) and frontend (frontend.mycustomdomain.com) apps. This change allowed the server to successfully set cookies for the client during the response process.

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

The map markers are nowhere to be found on the map when using Internet Explorer

Take a look at this code I wrote... var styles = [ { "featureType": "landscape", "stylers": [ {"weight": 0.1}, {"color": "#E7EDEF"} ] }, ... { "featureType": "poi.park", "elementType": "labels", "stylers": [ ...

Can data be transferred from node.js express to front-end HTML without requiring a page refresh?

Currently, I have developed a webpage that showcases all meetings with collapsible accordions. Initially, all the meetings are collapsed. However, when the user clicks on the meeting button (labeled as 'Audio' in the screenshot), a request contai ...

Launch a web application utilizing a node.js server hosted on Firebase

I am currently developing a web application using Vue. In this app, I have integrated "pusher" for real-time multi-user communication. I have set up a node.js server on port 5000 of a specific device within my local network. The app functions smoothly with ...

React-Query: executing a function after updating query data

After updating the cache in a form, triggered by a response from the server, I utilize setQueryData. However, following this cache update, my goal is to refocus on the form input field. Here are some details: Within my React application, I employ Recoil. ...

Updating the parameters when clicking on each pagination button: A guide

Does anyone have advice on implementing pagination? I am currently working on loading a datatable with a few records initially. Once the page is loaded, I want to be able to click on pagination buttons like next or any pagination buttons to display a new s ...

Instructions for implementing a "Load More" feature on blogs using either HTML or JavaScript

When retrieving blogs from a SQL Database, some of them tend to be lengthy. To tackle this issue, I plan on trimming each blog down to around 30 words (this amount may vary) and then incorporating a Load More link at the end. This link will enable users to ...

The method models.User.fromURI is unsuccessful

When I try to call models.User.fromURI as shown below: models.User.fromURI("spotify:user:" + user, function (user) { $(div).html("<b ><a style=\"color:#FFFFFF\" href=\"spotify:user:" + user.username + "\">" + us ...

Which is more efficient: filtering a JSON object or querying the database using ajax?

I am currently developing a product page that involves a selection of options that will impact the pricing of the items. The primary option allows users to choose a material, which then influences the available set of options. Within the database, there i ...

The specified project directory was not detected. Please restart Next.js in your updated directory

I am facing a challenge with running my NextJS web app on a VPS server with PM2 as the Process Management tool. Despite trying different approaches, I am unable to get it to run properly. I have a deploy.js file that successfully deploys my other NextJS an ...

Restrict the frequency of requests per minute using Supertest

We are utilizing supertest with Typescript to conduct API testing. For certain endpoints such as user registration and password modification, an email address is required for confirmation (containing user confirm token or reset password token). To facilit ...

Ways to activate jQuery validation when submitting a form instead of triggering it on blur

I am currently utilizing the Jquery Validation plugin to validate form fields upon submission. However, I have encountered an issue where incorrect email format triggers a validation message when moving to the next input field. This behavior is undesirable ...

Express application is experiencing difficulty displaying the modal

After creating a webpage in HTML with a modal that pops up on button click using jQuery and Bootstrap, everything works perfectly when the files are on my desktop (css, js, fonts, index.html). However, when I transfer the page into my Express application ...

if jade is being inconsistent

I am currently using expressjs in my app and have the following setup: app.get('/profile',index.profile); app.get('/',index.home); Within layout.jade, I have the following code: ... if typeof(username)!=='undefined' ...

Unlocking elements in Vue.js through functions

Looking to dynamically add a class to the label element when focusing on an input element below it. The current HTML and JS code I'm using is as follows: HTML: <label for="formProductId" ref="productIdLabel" class="form-element-title">Product ...

Troubleshooting jQuery Div Separation Problem

Currently, I am working on implementing resizable sidebars using jQuery and potentially jQueryUI. However, I am encountering an issue with the resizing functionality. Specifically, the right sidebar is causing some trouble in terms of proper resizing, wher ...

Guide on integrating a JavaScript control (JavaScript package) obtained from GitHub into my asp.net application

Hello everyone, I am a newcomer to GitHub and have some basic questions to ask. Recently, I downloaded the package from https://github.com/jspreadsheet/ce in .zip format for using in my asp.net web application. However, I am not sure how to incorporate the ...

Raphael and jQuery/JavaScript for user-selected array intersections

Hello everyone! This is my first time posting here, and I must say that I'm still quite new to JavaScript/jQuery/Raphael. Please forgive me if I make any mistakes or ask basic questions. :) I've been searching high and low for answers to my quer ...

Successful Ajax Form Submission but Fails to Receive Response

I am currently working on a feature where users can select a record from a menu to delete it from the database. Below this menu, there is a table displaying all records from the database. Even though the record gets deleted and reflects in the table upon m ...

Consistently fluctuating eTag in motion

My Node Express API has a default ETag configuration, but it keeps generating a new ETag every time I test hitting the server, even when the response content remains the same. I've compared the headers and tested with both API and static HTML content ...