Tips for transferring a variable between routes in express-js

Currently, I am using npm disco-oauth to authenticate with Discord. After authenticating in the main app.js file, I store the userKey in a cookie using cookie-parser. This allows me to access user information and the guilds that the user is a part of. However, I need to pass this user and filtered guilds information to a routes file where I handle dashboard routes. I prefer not to use queries or methods involving the URL to avoid cluttering the code.

The issue arises when attempting to provide cookieParser with an object like the one below:

app.get('/auth/discord', (req, res) => {
        if (req.cookies.userConfig.userKey) res.redirect('/guilds');
        else res.redirect(oauthClient.authCodeLink);
    })

    app.get('/login', async (req, res) => {
        try {
            let userKey = await oauthClient.getAccess(req.query.code);
            let userConfig = {
               userKey: userKey,
                 userID: " ",
                guilds: Guilds[]
            }
            await res.cookie('userConfig', userConfig);
            await res.redirect('/guilds');
        } catch (err) {
            res.render('error', {
                message: err.message,
           error: err
            });
        }
    });

    app.get('/logout', (req, res) => {
        res.clearCookie("userConfig")
        res.redirect('/')
    })

    app.get('/guilds', async (req, res) => {
        if (!req.cookies.userConfig.userKey) res.redirect('/');
        else {
            try {
                let user = await oauthClient.getUser(req.cookies.userConfig.userKey);
                let GUILDS = await oauthClient.getGuilds(req.cookies.userConfig.userKey)

                var Guilds = []
                await GUILDS.forEach(async g => {
                    if (g.permissions.includes("MANAGE_GUILD")) {
                        await Guilds.push(g)
                    }
                })
                 
                await res.render('guilds', {
                    user, 
                    Guilds, 
                    Servers: client.guilds.cache,
                    AdminIDs: keys.admin.discord_ids
                });

            } catch (err) {
                console.log(err)
                res.render('error', {
                    message: err.message,
                   error: err
                });
            }
        }
    })

The challenge lies in encountering a "cannot read property userKey of undefined" error when trying to implement the new cookie object. Strangely, it works fine when only passing the userKey. Is there a limitation on cookies or is my approach incorrect? Any guidance would be appreciated.

If the initial implementation remains problematic, I'm hesitant to modify the cookie further (referencing the comment in the code) and utilize it in other files and routes.

LATEST FUNCTIONAL VERSION

app.get('/auth/discord', (req, res) => {
        if (req.cookies.userKey) res.redirect('/guilds');
        else res.redirect(oauthClient.authCodeLink);
    })

    app.get('/login', async (req, res) => {
        try {
            let userKey = await oauthClient.getAccess(req.query.code);
            await res.cookie('userKey', userKey);
            await res.redirect('/guilds');
        } catch (err) {
            res.render('error', {
                message: err.message,
              error: err
            });
        }
    });

    app.get('/logout', (req, res) => {
        res.clearCookie("userKey")
        res.redirect('/')
    })

    app.get('/guilds', async (req, res) => {
        if (!req.cookies.userKey) res.redirect('/');
        else {
            try {
                let user = await oauthClient.getUser(req.cookies.userKey);
                let GUILDS = await oauthClient.getGuilds(req.cookies.userKey)

                var Guilds = []
                await GUILDS.forEach(async g => {
                    if (g.permissions.includes("MANAGE_GUILD")) {
                        await Guilds.push(g)
                    }
                })

                await res.render('guilds', {
                    user,
                     Guilds,
                    Servers: client.guilds.cache,
                    AdminIDs: keys.admin.discord_ids
                });

            } catch (err) {
                console.log(err)
                res.render('error', {
                    message: err.message,
                  error: err
                });
            }
        }
    })

Answer №1

Cookie values are structured as key value pairs delimited by semicolons. For more information on cookies, check out this link: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

If you're encountering issues, consider some troubleshooting methods to pinpoint the problem. The function cookieParser interprets the cookie data stored in req.headers.cookie. There may be specific processing logic within that module causing the issue.

To investigate further, set breakpoints in your debugger or use console.log to examine the contents of req.cookies and req.headers. This analysis can help identify any anomalies or errors possibly originating from cookieParser.

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

When the forward button is pressed multiple times in the carousel, the alignment changes

I recently noticed that the alignment of my carousel gets disturbed when I repeatedly click the forward button (>). How can I ensure that the carousel moves smoothly one item at a time when I click the forward or backward buttons? <div class="contai ...

The data submitted from the form did not successfully get inserted into the database row

Currently, I am working on integrating a new product into my products database using ajax with php and mysql PDO. The form is located in a separate HTML file and gets loaded into a Bootstrap modal when the "add product" button is clicked. Below you can fi ...

Tips for integrating results from ExpressJS res.render into a compressed ZIP archive

I've developed a function in ExpressJS that allows me to export a document as an HTML page: html: function (req, res) { Project.findOne( { req.params.project }, function (err, project) { res.contentType('text/html'); ...

Angular template driven forms fail to bind to model data

In an attempt to connect the model in angular template-driven forms, I have created a model class and utilized it to fill the input field. HTML: <div class="form-group col-md-2 col-12" [class.text-danger]="nameCode.invalid && nameCode.touched ...

ng-click stops functioning after ng-bind-html is compiled

I am struggling with integrating a directive into my AngularJS project. app.directive("dir", function($compile, $sce){ return{ restrict: "E", link: function(scope, element, attr){ scope.$watch('content',function() ...

Retrieve information from a URL and transform it into a JSON array

One of my functions looks like this: function retrieveJsonDataFromWebsite(url, callback) { let chunks = []; return require('https').get(url, res => { res.setEncoding('utf8') .on('data', (chunk) => { ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Having trouble with multi-file uploads in node.js?

<form action="http://localhost:3000/examples" method="post" enctype="multipart/form-data" accept="application/json"> <input type="text" name ="name"> <input type="text" name ="codedescription"> <input type="file" name ="fil ...

My Vue code encountered an error stating "unknown custom element" when trying to run it

As a beginner web developer, I am trying to implement CRUD operations in my Laravel and Vue project. Following the steps outlined in this tutorial, I have installed Datatable components into my application. Now, I need to integrate Datatable into my proje ...

The first time I try to load(), it only works partially

My script used to function properly, but it has suddenly stopped working. Can anyone help me figure out why? The expected behavior is for the referenced link to be inserted into target 1, while target 2 should be updated with new content from two addition ...

Struggling to retrieve error messages for empty or required fields while utilizing the Joi npm package

Joi package Version: ^17.6.0 I'm attempting to retrieve error messages for an array of object keys. See the Joi Validation Reference Image below: JSON Data: In the reference image, I have successfully validated most of the fields using Joi. However ...

Is there a way for React to detect when a property on an object within an array passed as props undergoes a change in its value?

My goal is to minimize extra work by updating a property within an object in an array of objects called onMouseEnter when hovering over an ApartmentCard that displays information about a specific apartment. The challenge lies in synchronizing the Map that ...

Why does Vuetify/Javascript keep throwing a ReferenceError stating that the variable is undefined?

I'm currently developing in Vuetify and I want to incorporate a javascript client for Prometheus to fetch data for my application. You can find the page Here. Despite following their example, I keep encountering a ReferenceError: Prometheus is not def ...

ReactJS component update issueUpdate function malfunctioning in ReactJs

Hey there, I could really use some assistance with a React component that I'm working on. I'm fairly new to React and what I'm trying to do is retrieve a list of available languages from the backend and display them in a dropdown. Once the u ...

Express: ways to wrap up a response

I am new to Node.js and encountering some issues that I need help with. I have organized my app into modules and controllers in app.js app.use('/api/sync', syncDataRouter) and in syncDataRouter.js const routes = function (con, Reading, Readin ...

What could have caused the textbox to not show up?

<html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <title>Dynamic Creation of Div Elements Using Javascript< ...

Asynchronous database calls within a loop that do not wait

I'm facing a challenge while trying to access a database during JSON parsing. This particular piece of code has become a nightmare for me: function loopColumns(val, cb){ db.one('select tag_name from t_tag where tag_id = $1', val) ...

Refresh WebPage automatically after a Servlet successfully uploads and processes an image

I have a webpage that includes an image and a button. When the button is clicked, it uploads the image by submitting a form to a file upload servlet. However, after successfully uploading the image, the servlet does not display it in the img tag. Here is ...

The state change in NextJS button becomes visible after the second click

An avid learner exploring Next.js. I am eager to create a component that displays the window width and height along with a Tailwind CSS breakpoint when a button is clicked, as a first step towards continuous display. I chose to implement a button click ev ...