Cómo proteger rutas en Express en Node.js

Aprende a proteger tus rutas en Express Node.js con ejemplos y código práctico para crear autorizaciones e implementar middlewares seguros.

6 nov 2025 • 3 min read • Q2BSTUDIO Team

Protección rutas Express Node.js

Proteger rutas es crítico en aplicaciones web modernas. En este texto explico cómo usar auth-verify, una libreria de Node.js para autenticacion, junto con middleware JWT en una aplicacion Express, traducido y adaptado para facilitar su implementacion y buenas practicas.

Instalacion y estructura basica: ejecutar npm install express ejs body-parser auth-verify path. Una estructura sencilla podria ser carpeta web-app donde estan views con register.ejs login.ejs dashboard.ejs y public con style.css y el archivo index.js en la raiz.

Resumen de index.js: importar express bodyParser auth-verify y path, configurar servidor y servir archivos estaticos desde public, usar bodyParser.urlencoded para formularios y establecer ejs como view engine. Inicializar AuthVerify pasando jwtSecret igual a supersecret y storeTokens igual a memory para un ejemplo simple. Mantener un arreglo en memoria users con objetos con username password role para fines didacticos.

Rutas basicas: pagina de registro GET register que renderiza la vista de registro y POST register que comprueba si el usuario existe, añade el usuario al arreglo y redirige o muestra un mensaje. Login GET login y POST login donde se valida username y password, se firma un JWT con auth.jwt.sign incluyendo payload con username y role y expiracion 1h y se pasa el objeto res para que auth-verify maneje la cookie automaticamente. Logout borra la cookie con res.clearCookie usando auth.jwt.cookieName o authToken y redirige a login.

Proteccion de rutas: proteger dashboard con auth.jwt.protect() como middleware, de modo que req.user contiene la informacion del token y se puede renderizar dashboard con los datos del usuario. Para rutas solo admin usar auth.jwt.protect({ requiredRole: admin }) y devolver un mensaje o contenido exclusivo para administradores. Asi se combina autenticacion basada en JWT con control de roles sencillo.

Vistas y estilo: crear views register.ejs login.ejs y dashboard.ejs con formularios basicos para username password y select de role. En public/style.css aplicar estilos ligeros para centrar el formulario y mejorar la experiencia. En produccion evitar almacenar contraseñas en texto plano y no usar el store memory; en su lugar usar una base de datos y hashing fuerte como bcrypt.

Buenas practicas y consideraciones de seguridad: usar variables de entorno para jwtSecret, habilitar HTTPS, marcar cookies como httpOnly secure sameSite strict, establecer expiracion de tokens y mecanismos de revocacion, almacenar tokens en redis o en un store central cuando la aplicacion escala, validar siempre el role en el servidor y no confiar en datos del cliente, y realizar pruebas de pentesting periodicas.

Despliegue y escalado: para entornos productivos integrar la aplicacion con servicios cloud para alta disponibilidad y seguridad. Nuestra experiencia incluye despliegues en plataformas cloud como AWS y Azure y podemos ayudar a migrar o desplegar aplicaciones con mejores practicas de seguridad y configuracion.

En Q2BSTUDIO somos una empresa de desarrollo de software que crea aplicaciones a medida y software a medida, con especializacion en inteligencia artificial y ciberseguridad. Si necesitas una aplicacion segura y escalable podemos ayudarte con desarrollo full stack, integracion con servicios cloud aws y azure, y auditorias de seguridad. Consulta nuestros servicios de desarrollo de aplicaciones a medida y nuestras soluciones de servicios de ciberseguridad. Ademas ofrecemos servicios de servicios inteligencia de negocio y power bi, ia para empresas, agentes IA y automatizacion para mejorar procesos y tomar decisiones con datos.

Resumen final: proteger rutas en Express con auth-verify y middleware JWT es directo y eficaz para gestionar sesiones y roles. Implementa siempre buenas practicas de seguridad, usa almacenamiento de tokens fiable y considera escalar con servicios cloud y monitoreo. Si quieres que te ayudemos a implementar una solucion a medida segura y optimizada, contacta con Q2BSTUDIO para proyectos de inteligencia artificial, servicios cloud aws y azure, power bi y mucho mas.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat