Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Node login not working: I think it's stuck in a loop

Hello lovely people, here's my code. Can anyone help me? Thank you!

Browser tells me that it has redirected me too many times, I've read somewhere else that it means it might be stuck in a loop... Or maybe something else is wrong... I'm doing this for an online course and the teacher doesn't explain much, so it's quite confusing D:

I'm new to coding, please be kind

import express from "express";
import config from "./config";
import morgan from "morgan";
import cors from "cors";
import path from "path";
import ejs from "ejs";

var session = require('express-session');



var logger = require('morgan');
var cookieParser = require('cookieParser');

var loginRouter = require('./routes/admin/login');


import contact from "./routes/contact";


const app = express();

app.set("PORT", config.PORT);

app.get("/", (_, res) => res.render("admin/login.hbs"));

app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    secret:'dasajk453sdhas234dkl534jasdjk',
    resave:false,
    saveUninitialized:true
}));


var secured = async(req,res,next) => {
    try{
        if(req.session.id_usuario){
            return res.redirect('/home');
        }else{
            res.redirect('/admin/login');
        }
    }catch(error){
        console.log(error)
    }
}


app.use(cors());
app.use(morgan());
app.use(express.urlencoded({
    extended: false
}));
app.use(express.json());

app.use("/contact", contact);
app.use('/admin/login', loginRouter);

app.use(logger('dev'));
app.get(cookieParser());

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.get("/home", secured, (req, res)=>res.render("index.hbs"));



export default app;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is because you are doing recursive redirects to /home.

Here when u r doing post request to /admin/login

router.post('/', async(req,res,next) => {
    try{
    var usuario = req.body.usuario;
    var password = req.body.password;

    console.log(req.body);

    var data = await usuariosModel.getUserandPassword(usuario,password);

    if(data != undefined){
        req.session.id_usuario = data.id; <------ You are adding id to session here
        req.session.nombre = data.usuario;
        res.redirect('/home'); <------- At this point u r redirecting to '/home' 
    }else {
        res.render('admin/login', {
            layout: 'admin/layout',
            error:true
        });
      }


    }catch (error){
        console.log(error);
    }
});

On coming to /home, you are checking secured using middleware

var secured = async(req,res,next) => { <----- you are checking for `/home`
    try{
        if(req.session.id_usuario){ <----- Here u r again checking if id is present, then again redirect to `/home`, which is creating a loop of redirects. You need to resolve this.
        //You need to do a next() here, i guess
            return res.redirect('/home');
        }else{
            res.redirect('/admin/login');
        }
    }catch(error){
        console.log(error)
    }
}

Note: This should resolve ur error. Check your middleware otherwise and try each routing flow for clarification

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!