The value of req.session.returnTo is not defined

I have implemented passport for user authentication using discord oauth2. I want the users to be redirected back to the original page they came from instead of being directed to the home page or a dashboard.

Even though I tried saving the URL in the session as mentioned here, it seems that the information is not retained for the next request.

This is the middleware for pages requiring authentication:

module.exports = (req, res, next) => {
  if (req.user) {
    next();
  }
  else {
    req.session.returnTo = req.originalUrl;
    res.redirect('/auth');
  }
};

Authentication route:

router.get("/auth", passport.authenticate("discord"));

router.get("/auth/redirect", passport.authenticate("discord", {
  failureRedirect: "/auth/forbidden"
}), (req, res) => {
  console.log(req.session); // why is returnTo no longer present?
  res.redirect(req.session.returnTo || '/');
  delete req.session.returnTo;
});

The console log confirms successful authentication, but the returnTo field is missing.

Answer №1

Greetings! I encountered a similar issue and found a solution. You can resolve it by including keepSessionInfo: true in the passport.authenticate function.

router.get("/auth", passport.authenticate("discord", {
    failureRedirect: "/auth/forbidden", keepSessionInfo: true
}), (req, res) => {
    console.log(req.session); // Is the returnTo attribute missing now?
    res.redirect(req.session.returnTo || '/');
    delete req.session.returnTo;
});

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

Leveraging nodemailer and handlebars for personalized email templates

I'm encountering an issue and struggling to pinpoint what exactly is causing it. Whenever I execute my code, the following error message pops up: [Error: ENOENT: no such file or directory, open 'C:\Users\Alex\Desktop\emailtes ...

Steps for deleting a game objectWould you like to learn how to

What is the process of creating an object that can eliminate itself automatically? var item = []; function selfDestruct() { this.destroy = () => { this = false; } } function initialization() { item[0] = new SelfDestruct(); item[0].destroy( ...

An unusual phenomenon in the controller hierarchy causing issues with accessing the parent scope in AngularJS

Recently delving into the world of angularjs, I encountered something perplexing that seemed like a glitch in the controller hierarchy when it comes to accessing the parent scope. Here are two code snippets that I believed should both function properly bas ...

Are you looking for methods to alter the elements of a webpage prior to viewing it?

I have created a page with the intention of using it as a tool, but I am facing some challenges due to my limited experience in this field. As a newcomer, I am struggling to achieve certain goals: - My objective is to modify the values of an element on a p ...

Is there a modal confirmation feature available in Salesforce?

if ((Modal.confirm && Modal.confirm('some unique text')) || (!Modal.confirm && window.confirm('same but different text'))) navigateToUrl('another link here','ANOTHER DETAIL','submit'); I am curious about t ...

Is there a way to prevent redirection to the homepage after submitting a login form?

Having trouble with my Single Page application: every time I refresh the page after rendering the login form, it goes back to the homepage. How can I prevent this and make sure the page stays on the login form even after a refresh? This is what my homepag ...

How does NodeJs handle ongoing tasks and processes seamlessly?

One interesting concept is the Event Loop, which accepts callbacks and executes them as needed. As far as I understand, this operates on a single thread event loop, meaning only one callback is executed at a time. Consider the following example: setInterv ...

Getting the value from a label and then setting it as the innerHTML of document.getElementById('label')

I have successfully implemented a JavaScript Google Maps functionality, but now I am facing an issue where I need to retrieve the type of HTML control and set it to JavaScript. Specifically, when attempting to extract the value from lblTitle, it is not f ...

Using jQuery to display handlebar helpers

I am working on inserting a code snippet into my main template (using handlebars) with the help of jquery. var addSnippet = function(data){ return ` <div class='some class'> {{{formatDate ${data.created_at} 'MMM DD ...

Show only specific data from JSON results

I am trying to display a specific cryptocurrency's price without the need for curly braces or explicitly stating "USD". Currently, it appears as {"USD":0.4823} when using the following code: <script> $(document).ready(function () { ...

The table width is malfunctioning on Firefox when viewed in HTML

I have been puzzled by the fact that I am unable to adjust the width of the table th in Firefox browser to the smallest value. However, in Chrome browser, this functionality works perfectly. I simply want to divide the values of my td into three rows as sh ...

Parsing JSON data into a template using a route for faster performance

I am having difficulty extracting data from a mongodb using a specific route. My objective is to retrieve the title fields from each object. Below is the schema: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var GiveSch ...

The correct assertion of types is not carried out during the initialization of generics through a constructor

I am encountering a minor issue with TypeScript, and I am uncertain whether it is due to a typo on my part or if TypeScript is unable to correctly infer the types. Let me provide all the necessary code to replicate the problem: interface IRawFoo { type: s ...

Utilize React to iterate through a dictionary and display each entry

Essentially, I am pulling data from my API and the structure of the data is as follows: { "comments": [ { "user": "user1" "text": "this is a sample text1" }, { "user": "user2" "text": "This is a simple text2" }, } ...

Steps for displaying an image link on an aspx webpage

Is it possible to have the full-size image open on http//example.com/image.aspx when the thumbnail is clicked, instead of http//example.com/images/image.jpeg? I am looking for a solution that does not require creating individual pages for each image or edi ...

JavaScript (specifically, using jQuery) in conjunction with AJAX

After using validation with jQuery in JavaScript and applying it to ASP.NET controls within an AJAX update panel, I encountered a problem. The validations are working correctly, but the event of the button control is still being executed despite the valida ...

Ceasing the response in case the document cannot be located

My code checks for the existence of an id in the database. If it doesn't exist, it should stop the logic immediately. However, instead of returning "The provided Project Id does not exist in our database.", it currently returns "Please send all the r ...

Axios is retrieving an incorrect URL through Express

I am currently developing a MERN stack application that mimics Tinder's functionality. My backend server is hosted on localhost:8001, and the frontend is on localhost:3000. I have opted to use MongoDB for storing the data related to tinder cards. Be ...

Encountering NaN in the DOM while attempting to interpolate values from an array using ngFor

I am working with Angular 2 and TypeScript, but I am encountering NaN in the option tag. In my app.component.ts file: export class AppComponent { rooms = { type: [ 'Study room', 'Hall', 'Sports hall', ...

What could be causing my update function to not run when I refresh the page?

As a non-developer trying to learn react.js, I am working on a section of my website that needs to update every few seconds with new content like a photo, header, and body text. I've encountered an issue where the data refreshes correctly after the p ...