Guide to verifying the presence of cookies by name in the browser and granting access to the specific page accordingly

In the process of developing an authorization system with Express, Node, and MySQL, I decided to utilize JWT tokens for user authorization. After successfully storing the JWT token in cookies, my next step is to verify if the token exists in the cookie before granting access to the page. If the token does not exist, the user should be redirected to the login page.

Answer №1

Develop a middleware that retrieves a specific cookie from req.cookies and validates if it contains a legitimate jwt token. If the token is valid, proceed to call next() to allow the request routing to move forward. Otherwise, refrain from calling next() and instead use res.redirect("/login").

const cookieParser = require('cookie-parser');

app.use(cookieParser(), function(req, res, next) {
    let token = req.cookies.myCookieName;
    if (token && verify(token)) {
        next();
    } else {
        res.redirect('/login');
    }
});

You will need to provide the implementation for the verify() function which verifies the validity of the token obtained from the cookie. Specify the name of the cookie as demonstrated here with myCookieName (the name you previously used to store the jwt token).

If the verify() function requires an asynchronous operation (e.g., querying a database), the code can be adjusted to only trigger the next() function upon successful completion of the asynchronous callback.

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

Oops! An error occurred: Uncaught promise rejection - invalid link found for ProductListComponent

I am currently in the process of learning Angular and Ionic, but I am feeling a bit confused as to where my mistake is. I have looked at other questions, but I still can't seem to figure it out. Can anyone provide some assistance? Perhaps someone has ...

In the world of web development, utilizing HTTP GET

Creating a website using angular 4, express, and mongo for the first time has been quite challenging. I am struggling with implementing get requests properly to fetch data from the server. I realized that these requests are used for retrieving information ...

Seeking guidance on the authentication of users on the front end and back end

Currently, I have a mock expressjs server running in the background and ember (ember-simple-auth) with the ember-simple-auth-token addon on the frontend. The authentication is done using JWT tokens. As of now, when a user submits their credentials, a new t ...

Is it possible to refrain from using the object variable name in an ng-repeat loop?

When utilizing an ng-repeat directive to loop through an array, the syntax requires ng-repeat="friend in friends". Inside the template, you can then use the interpolation operator like this {{friend.name}}. Is there a way to directly assign properties to ...

Displaying an array of objects in the MUI Datagrid interface

I have integrated Redux into my project to retrieve data from the API, and this is a snapshot of the data structure: https://i.stack.imgur.com/jMjUF.png My current challenge lies in finding an effective way to display the information stored within the &a ...

Exploring layered data through specific properties

Imagine a scenario where I have an array filled with data. Each element in this array is an object that could contain: an id some additional data a property (let's name it sub) which may hold an array of objects with the same properties (including t ...

Enhance the "content switcher" code

I have been working on improving my "contenthandler" function. It currently changes different articles when I click different buttons, which I am satisfied with. However, I believe there may be a better approach to this and would appreciate any advice on h ...

How can I determine the size of the custom options dropdown in Magento?

I'm facing a challenging issue that I can't seem to crack. It might be because I'm still learning the ropes and struggling with technical jargon. Please bear with me as I try to explain my problem. Here is a summary of what I'm trying ...

Utilizing a switch statement for form validation

Currently, I am in the process of creating a form validation that involves two conditions for validation. I'm considering using a combination of switch case and if else statements. Would this be an appropriate approach or is it generally discouraged? ...

A tool developed in Javascript that allows for the conversion of .ini files to .json files directly on the client

Does anyone know of a JavaScript library that can convert .ini files to .json files on the client-side? I checked out this library, but it doesn't meet my requirements. Here is an example of an .ini file: [Master_Settings:1] Model Name=RC-74DL IP Ad ...

Exploring the capabilities of Vue.js, including the use of Vue.set()

Just starting out with Vuejs and I have a query regarding the correct approach to achieve what I want. My Objective I aim to have some dates stored in an array and be able to update them upon an event trigger. Initially, I attempted using Vue.set, which ...

Activate the download upon clicking in Angular 2

One situation is the following where an icon has a click event <md-list-item *ngFor="let history of exportHistory"> <md-icon (click)="onDownloadClick(history)" md-list-avatar>file_download</md-icon> <a md-line> ...

How can I retrieve JSON data from an AJAX request on an HTML page?

How can I display my JSON data on an HTML page using this JavaScript code? $.ajax({ url : 'auth.json', type: "GET", dataType : "jsonp", success: function(result) { $.each(result, function(i, v) { // Loop through each record in ...

V-Calendar is not displaying the accurate dates

https://i.stack.imgur.com/zk4h7.png The image displays dates starting on June 1, 2022, which should be a Wednesday but appears as a Sunday on the calendar. This issue affects all months as they start on a Sunday instead of their respective weekdays. The p ...

Tips for updating border color when focused with styled-components

How can I change the border color of an input on focus using styled-components and React? Here is the code snippet I am currently using: import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; const String ...

Managing MUI form fields using React

It seems like I may be overlooking the obvious, as I haven't come across any other posts addressing the specific issue I'm facing. My goal is to provide an end user with the ability to set a location for an object either by entering information i ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

Retrieve isolated scope of directive from transcluded content

I am not certain if it is possible, but I am essentially looking for a reverse version of the '&' isolate scope in AngularJS. You can check out this Plunkr to see an example. In essence, I have created a custom directive that provides some r ...

Issue with useEffect EventListener in REACT HOOKS

Recently, I attempted to create a simple Snake-Game using REACT. Everything was going smoothly until I encountered an issue with using useEffect for moving the "snake" when a keydown event is triggered. The challenge arose when trying to implement moveSnak ...

How can I restrict the navigation buttons in FullCalendar to only allow viewing the current month and the next one?

I recently downloaded the FullCalendar plugin from Is there a way to disable the previous button so that only the current month is visible? Also, how can I limit the next button so that only one upcoming month is shown? In my header, I included this code ...