Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

260
Vistas
express-session/cors/Axios returns 401 (unauthorized)

UPDATE: it aparently works on firefox, I was using brave. I guess it's blocking the cookie with the session?? I don't know what to do about that.


I'm building an app with Vue, connecting through Axios to an API made with express.

I'm trying to use express-session to manage login sessions and auth. On my localhost it works great, but when I tried to use it from the site hosted on heroku, it breaks. The middleware that checks whether the session has an usuario property blocks the call.

I'm pretty sure it has to do with https instead of http. I tested it on localhost https with some generated credentials and it broke the same way.

The endpoint for login is quite long, but basically checks if the password you gave it is correct, and if it is, it sets req.session.usuario to an object with some user data. After that, when I check again for the session, usuario is not set.

The CORS middleware:

const cors = require("cors");

const whitelist = ["https://localhost:8080", "https://hosted-client.herokuapp.com"];
const corsOptions = {
    credentials: true,
    origin: (origin, callback) => {
        if (whitelist.includes(origin))
            return callback(null, true);

        //callback(new Error("CORS error"));
        callback(null, true);
    },
};

module.exports = cors(corsOptions);

The session middleware:

const Redis        = require("ioredis");
const connectRedis = require("connect-redis");
const session      = require("express-session");

const RedisStore = connectRedis(session);
const redisClient = new Redis(
    process.env.REDIS_PORT,
    process.env.REDIS_HOST,
    {password: process.env.REDIS_PASSWORD}
);

module.exports = session({
    store: new RedisStore({ client: redisClient }),
    secret: process.env.SECRET,
    saveUninitialized: false,
    resave: process.env.STATE_ENV === "production",
    proxy: true,
    cookie: {
        secure: process.env.STATE_ENV === "production",
        httpOnly: true,
        sameSite: "none",
        // maxAge: 1000 * 60 * 30, // 30 minutos
    },
});

A simple test auth middleware:

module.exports = function (req, _, next) {
    if (!req.session || !req.session.usuario) {
        const err = new Error("No se encontró una sesión");
        err.statusCode = 401;

        next(err);
    }
    next();
}

The Axios instance on the client:

require("dotenv").config();
import axios from "axios";

export default axios.create({
    baseURL: process.env.VUE_APP_API,
    headers: {
        "Content-type": "application/json",
    },
    withCredentials: true,
});

I'm not sure if that's enough info, if not let me know.

over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda