The login middleware for Express is not functioning as expected

Being new to web development, I am keeping my expectations low.

I have a sign-in page that saves the entered email as a cookie. The account page deletes this cookie when the user logs out by pressing a logout button.

I am attempting to create middleware that will redirect the user to the sign-in page if the cookie is deleted (i.e., the user logs out).

Everything works as intended when the cookie is set up. However, pressing the logout button does not render the sign-in page.

In the sign-in route, the script looks like this:

const fs = require('fs');
const path = require('path');
const { v4 } = require('uuid');
const express = require("express");
const cookieParser = require('cookie-parser'); 

const { containsObject, getUsers } = require('../Auth/auth.cjs');
const {userExists} = require('./signin.cjs')

const router = express.Router();

router.get('/', (req, res) => {

    const {cookies} = req;

    if(cookies['email']){
        res.redirect('/main');
    }
    else{
        res.render('SignIn/signin');
    }
})

router.post('/', async (req, res) => {

    const user = {
        email:req.body.email,
        password:req.body.password,
    }
        
    const result = await userExists(user);

    if(result){
        res.cookie('email', req.body.email);
        res.redirect('/main');
    }
    else{
        res.render('SignIn/signin', user)
    }

})

module.exports = router;

The logout button is a form element! - I couldn't come up with anything easier.

  <form method="post">
            <input type="submit" value="Log out"/>
  </form>

Logout route:

const fs = require('fs');
const path = require('path');
const { v4 } = require('uuid');
const express = require('express');
const { route } = require('../SignIn/signin');
const { compile } = require('ejs');

const {getUser, getPostsFromUser} = require('./account.cjs')

const router = express.Router();

router.get("/", async (req, res) => {
    const {cookies} = req;
    const email = cookies['email'];
    const userResponse = await getUser(email);

    const user = {
        username:userResponse['username'],
        email:userResponse['email'],
    }

    console.log(await getPostsFromUser(user));

    res.render('Account/account', user);
})

router.post('/', (req, res) => {
    
    // const {cookies} = req;
    res.cookie('email', '', {expires: new Date(0)});
    res.clearCookie("email");
    res.redirect('/sign')
})

module.exports = router;

Main file:

const { localsName } = require("ejs");
const express = require("express");
const app = express();
const cookieParser = require('cookie-parser');

const users = []
let loggedIn = false

app.set('view engine', 'ejs');

app.use(cookieParser());
app.use(express.static('public'));
app.use(express.urlencoded({extended:true}))

app.use((req, res, next) => {
    const {cookies} = req;
    console.log(cookies['email'])

    if(cookies['email'] == undefined){
        return res.redirect('/sign');
    }
    else{

        next();
    }
})

app.get('/', (req, res) =>{
    res.redirect('/sign')
})

const signRouter = require('./views/SignIn/signin.js');
app.use('/sign', signRouter);

const authRouter = require('./views/Auth/auth.js');
app.use('/auth', authRouter);

const mainRouter = require('./views/Main/main.js');
app.use('/main', mainRouter);

const addPostRouter = require('./views/Add_post/add_post.js');
app.use('/add-post', addPostRouter);

const accountRouter = require('./views/Account/account.js');
app.use('/account', accountRouter);

app.listen(3000)

I've attempted various approaches, but I can't seem to figure out why the page won't render smoothly.

Answer №1

The issue arose when I placed the middleware above the signin route, resulting in a circular redirect. This occurs because without being signed in, the user is redirected to the signin router first, which then tries to render.

To fix this problem, simply move the middleware below the signin route in the server.js file. The updated code will look like this:


app.get('/', (req, res) =>{
    res.redirect('/sign')
})

const signRouter = require('./views/SignIn/signin.js');
app.use('/sign', signRouter);

app.use((req, res, next) => {
    const {cookies} = req;
    console.log(cookies['email'])

    if(cookies['email'] == undefined){
        return res.redirect('/sign');
    }
    else{

        next();
    }
})

const authRouter = require('./views/Auth/auth.js');
app.use('/auth', authRouter);
// other routes

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

Tips for successfully navigating and utilizing function values

I have developed models named (user.js). module.exports.show_deatils = function(req,res,callback){ var resultArray=[]; mongo.connect(url,function(err,db){ assert.equal(null,err); var cursor=db.collection('users&apos ...

Is it recommended to employ cluster connection within my Redis client when utilizing Azure Redis Cluster?

It seems that the Azure documentation on clustering can be a bit confusing. According to the docs: Will my client application need any modifications to support clustering? Once clustering is activated, only database 0 will be accessible. If your client ...

Encountering an error when trying to use variable values for D3 chart instead of static json files, which are working

Our challenge is to retrieve JSON values from a variable (data) and pass them to D3 as JSON input. However, we are encountering an error in Firebug stating "data.links is not defined". The chart displays correctly when we use the JSON values from the sampl ...

Multiple instances of Ajax requests being submitted

I am currently working on updating the validation for my forms. The validation itself is functioning properly, but I have encountered an issue where if no validation errors occur, the form submits multiple times based on the number of submission attempts b ...

Unique shader customized to achieve the desired phong effect

I am looking to develop a simple, yet effective shader for my terrain mesh. This shader should utilize different diffuse and normal textures based on the color of the world map image, and should be able to receive shadows and interact with lighting. The d ...

Populate the database with values when the button is clicked

Hello, I encountered an issue with my code where it is adding empty values to the database when attempting to enter input text values. I am using PHP and MySQL for this task. <html> <body> <input type="text" name="value" /> <input ...

Exploring and retrieving JSON objects in multidimensional arrays

I'm facing a challenge with the code snippet provided below. var employees = [ { firstName: "John", lastName :"Doe", qualification: {Diploma: 'IT Software' , Degree: 'Software Engineering'} }, { firs ...

How can React Native on Android open another app?

I'm encountering an issue while attempting to open another app () from my own app. Despite numerous tutorials directing me to the Play Store only, I came across a GitHub link (https://github.com/FiberJW/react-native-app-link) that allows for app openi ...

jspdf generates blank PDF files

I am trying to use JsPDF to generate a PDF from content within a Section tag. I have followed various guides but none of them seem to be working for me. Since there is no demo code available, I am turning to this platform in hopes of finding a solution. A ...

All-in-one Angular script and data housed within a single document

Context I want to design a personalized "dashboard" to assist me in staying organized. This dashboard will help me keep track of the issues I am currently handling, tasks I have delegated, emails awaiting response, and more. While I am aware of project ma ...

JavaScript code is functioning properly on Chrome and Internet Explorer, however, it may not be working on FireFox

Despite searching through the console, I am unable to find a solution to this issue. There are two images in play here - one is supposed to appear at specific coordinates while the other should follow the mouse cursor. However, the image intended to track ...

The script utilizing Typescript and ExpressJs failed to execute

Looking to transition my simplistic server code from Coffeescript to Typescript. Here is the original snippet: express = require("express") app=express() app.use(express.static(__dirname)) app.set("views", __dirname + "/views") app.set("view engine", "jad ...

Background image of HTML Iframe element does not display - Inline style block

https://i.stack.imgur.com/JW26M.png After setting the iframe's innerHTML using this line of code: iframedoc.body.innerHTML = tinyMCE.activeEditor.getContent(); The styles for the elements within the iframe are contained in an inline style block. Ho ...

Deciphering a PHP json_encode response using JavaScript

Consider this scenario where I am using json_encoding for my array and displaying it: $key = $this->key; $sql = "SELECT * FROM Requests"; $result = $this->db->query($sql); ...

Employing Jquery for restricting checkbox selection based on parent HTML elements

UPDATE I am looking to limit checkbox selection in specific sections on the same page. To prevent conflicting inputs from different sections, I believe using the label selector <label data-addon-name="xxx"> as a separator is the best appro ...

Tips for modifying the content of a div within an HTML document after a certain period of time has elapsed, and then repeating the process

Currently, I am in the process of developing an Android app that will function as a Digital Display. One of the challenges I am facing involves displaying an HTML page with multiple regions or boxes, each containing various items that need to switch dynami ...

Tips for displaying a popup modal when a link is clicked with ajax technology

I am facing an issue with my popup modal. When a user clicks on a link, the modal appears but without any content. I am new to ajax and feeling a bit confused about what steps to take next. Below is the HTML code snippet: <div class="modal fade&quo ...

Placing a dropdown menu on top of an image

I currently have a slightly rotated menu bar with two buttons as an example: https://i.stack.imgur.com/0sI2P.jpg Due to the rotation, normal HTML handling is not feasible. I am considering using a <map> element to create hyperlinks over the menu it ...

Establishing a pre-selected option in a drop-down menu

I am working on a dropdown list and my goal is to have the default option selected when the page loads <b>Filter Within Months:</b> <select class="btn green" ng-model="myOptions" ng-options="i.label for i in items track by i.id" ng-change= ...

The onreadystatechange function is not triggering

For some reason, the onreadystatechange callback function is not triggering in asynchronous mode. After testing the post request in synchronous mode, it seems that the post itself is functioning correctly (the testing code used for synchronous mode has b ...