Utilizing req.session in an Express application with Angular (written in TypeScript) when deploying the backend and frontend separately on Heroku

I'm currently facing an issue where I am unable to access req.session from my Express app in Angular. Both the backend and frontend are deployed separately on Heroku. I have already configured CORS to handle HTTP requests from Angular to my Express app.

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json,X-XSRF-TOKEN,CSRF-Token,X-CSRF-Token');
next();
});

However, I am encountering difficulty in handling or retrieving the request session as it always appears empty. While I was able to retrieve the connect.sid in my Express app when making an HTTP GET request, it does not persist when another request is made in Angular. Consequently, each time the Angular app is refreshed, the session ID also gets refreshed. I require the cookie to persist so that I can utilize it for a POST request (e.g., initiating an HTTP GET request to Angular with the response being a CSRF token, followed by a subsequent POST request using the requested CSRF token for login). Since every session ID is different for each request, the CSRF token becomes invalid. All Express sessions are stored in MongoLab through the connect-mongo npm module.

app.use(session({
    secret : process.env.sessionKey,    
    httpOnly: true,
    resave : true,
    saveUninitialized: true, 
    store  : new mongoStore({ mongooseConnection: mongoose.connection }),
    cookie : { maxAge: 60 * 60 * 1000}
}));

The HTTP GET and POST methods in my Angular App are functioning correctly, indicating that CORS has been properly configured. Upon inspecting the response header when accessing the route URL ('login') in Angular to initiate the HTTP GET request, I noticed that the cookies (cookies.sid) were set in the header. However, I am unsure how to store this session ID from the cookies in order to use it for subsequent requests in the Angular app (such as logging in).

https://i.sstatic.net/N9I6r.jpg

Answer №1

If you are looking to retrieve a stored cookie from the browser, simply utilize the function provided below wherever it is needed:

function fetchCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return null;
}

To verify the cookie's name, navigate to the Application tab within your browser's developer console. In this instance, look for connect.sid. Once identified, call the function:

fetchCookie(<cookie-name>); // You can then make use of the retrieved value.

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

Ordering a list of IP addresses using Angular Material table sorting

Here is an example I am baffled by the fact that Material Table sorting does not properly arrange the table. I have created a stackblitz example to demonstrate this. Expected order - Sorting lowest IP first: "10.16.0.8" "10.16.0.16" & ...

A guide on connecting multiple select components to a unified Angular 6+ reactive form without triggering redundant updates

I am facing an issue where I need to connect multiple input components to a single angular reactive form, but encounter two main obstacles: By default, only the form in which user input occurs gets updated If I use [(ngModel)] it does work, but it trigge ...

Retrieving updated data from a service does not trigger a refresh of the view

Having an issue with rendering data obtained from a service. Here is the situation: The service retrieves values from a distant API using an Observable: @Injectable() export class myService { constructor(private http: Http) { } getData(listLength: num ...

Setting the base path for npm tests: A step-by-step guide

I am currently working on a web application that utilizes Angular as the front-end technology and Java Spring Boot as the backend. https://i.sstatic.net/IWPNZ.png In the screenshot above, you can see that I have created a new directory within the root fo ...

Exciting New Feature in WebStorm 2016.3: TypeScript Tooltips Inspired by VS Code!

One of the great features of Visual Studio Code is its excellent support for TypeScript, such as type inference displayed in tooltips. However, by default in WebStorm, only Console/Errors are visible in the tool window when hovering over a function without ...

Issue with Angular httpClient not correctly handling PHP error objects

My current task involves integrating with an older php login api that returns a success or error message response object. After connecting with the correct credentials, I receive the success object. However, if the credentials are incorrect, I receive the ...

Advancing the utilization of custom Angular input fields

I've developed a unique Angular input element that utilizes a textarea as its primary input field. Is there a way for me to pass along the enter key event to the main form? ...

Displaying Child Component in Parent Component After Click Event on Another Child Component: How to Implement Angular Parent/Children Click Events

After delving into Angular 7 for a few weeks, I find myself faced with the challenge of toggling the visibility of a child component called <app-child-2> within a Parent component named <parent>. This toggle action needs to be triggered by a cl ...

Maintaining the essence of generics while encapsulating functions

I am currently facing a challenge in defining a function that can wrap any other function while maintaining the parameter types and return type. I have managed to achieve this when the function does not use generics, but I am encountering difficulties wi ...

Unexpected behavior encountered when running Angular 8 radio button checked function

I have an Angular 8 web app with some unique logic implemented as shown below: HTML: <div *ngFor="let item of selectedItems;"> <input type="radio" [(ngModel)]="mySelectedItem" [value]="item.key" (ngModelChange)="setCh ...

Creating a personalized connect function in Typescript for react-redux applications

Currently, I am in the process of migrating a large and intricate application to Typescript. One specific challenge we are facing is our reliance on createProvider and the storeKey option for linking our containers to the store. With over 100 containers in ...

Tips for implementing debounce functionality in mui Autocomplete

How can I debounce the onInputChange function within the MyAutocomplete component? export interface AutocompleteProps<V extends FieldValues> { onInputChange: UseAutocompleteProps<UserOrEmail, true, false, false>['onInputChange']; } ...

Error: Typescript foreach loop encountering 'Expression yields void type'

Currently, I am working on setting up a cron job to monitor the completion of my tournaments and trigger some specific code upon completion. For reference, I came across this example: During deployment of my code, an error popped up as follows: ERROR: fu ...

What is the process of determining if two tuples are equal in Typescript?

When comparing two tuples with equal values, it may be surprising to find that the result is false. Here's an example: ➜ algo-ts git:(master) ✗ ts-node > const expected: [number, number] = [4, 4]; undefined > const actual: [number, number] ...

What is the best way to add all IDs to an array, except for the very first one

Is there a way to push all response IDs into the idList array, excluding the first ID? Currently, the code below pushes all IDs to the list. How can it be modified to exclude the first ID? const getAllId = async () => { let res = await axios({ m ...

Cross-origin resource sharing (CORS) restrictions in play for Dockerized Django REST and Angular

Today, I made the decision to dockerize an existing Django REST + Angular app. While the website is displaying correctly, CORS requests are currently being blocked. The CORS policy is blocking access to XMLHttpRequest at 'http://localhost:8000/bran ...

Send all Apache requests within a specified URL directory to a particular file, while directing all other requests to a different file

I am in the process of setting up an Angular application along with a basic PHP CRUD API backend on my Raspberry Pi 3 using Apache. My goal is to configure the mod_rewrite rules to first check for existing files or directories, then redirect requests for t ...

Struggling with defining types in NextJs when using dynamic imports in Typescript and NextJs

I have successfully created a component that utilizes next/dynamic to import react-icons only when needed. However, I am struggling to properly define the TypeScript types for this component. Despite this issue, the component itself is functioning as expec ...

Having trouble incorporating a canvas created with html2canvas into the addHTML() method of jspdf

I am working on developing an application using angular5 and I am attempting to incorporate HTML by utilizing the jspdf.addHTML() function in conjunction with html2canvas. const content = this.vc_print_section.nativeElement; html2canvas(content).then(can ...

Setting up Typescript classes that inherit from one another with diverse properties for each subclass

I'm fairly new to Typescript and currently grappling with how to effectively manage class inheritance when base classes have distinct properties. Essentially, I have a base class where I aim to define shared functionality and a series of subclasses w ...