DEV Community

Cover image for Building a Secure Node.js REST API with JWT Auth and Role-Based Access Using MySQL
vdelitz for Corbado

Posted on • Originally published at corbado.com

Building a Secure Node.js REST API with JWT Auth and Role-Based Access Using MySQL

Read the full article here


Introduction: Token-Based Authentication in Modern Node.js APIs

Implementing secure authentication is a critical requirement for web and mobile applications. This guide explains how to set up Node.js JWT authentication in an Express.js REST API, with robust MySQL user roles and access control. By using JWT (JSON Web Token) for token-based authentication, this approach enables scalable and stateless user sessions — ideal for distributed and cloud applications.


Project Structure and Core Technologies

The project features a clear structure for maintainability and scalability, including directories for configuration, controllers, middlewares, models and routes. The technology stack includes:

  • Node.js and Express 4 for backend logic and routing
  • Sequelize ORM for interacting with MySQL 8 databases
  • JWTs for stateless authentication
  • bcryptjs for secure password hashing
  • CORS middleware for cross-origin requests

This stack is widely used in the Node.js ecosystem to build secure APIs with role-based access and performant MySQL integration.


Setting Up the Application

Begin by creating a new Node.js project, installing essential dependencies (express, sequelize, mysql2, cors, jsonwebtoken, bcryptjs) and configuring ES modules in package.json. Initialize Sequelize for MySQL connectivity and define models for users and roles — enabling many-to-many relationships for flexible role assignment. The Express server is set up to parse JSON, handle CORS and connect to routes.


MySQL Database and Sequelize ORM

Database settings are maintained in a dedicated configuration file and should use environment variables for production. Sequelize models define the structure for users (containing username, email and hashed password fields) and roles. Associations allow each user to have multiple roles and vice versa.


Role-Based Access Control with JWT

JWTs are integrated to provide stateless authentication. Upon successful login, the API returns a signed JWT that the client stores (e.g., in local or secure storage). Protected routes require the JWT in the Authorization header (Bearer ), which is verified by custom Express middlewares.

Middleware functions manage:

  • User authentication via JWT verification
  • Role-based permissions (e.g., admin, moderator, user)
  • Input validation during signup to avoid duplicate usernames/emails

Controllers and Route Management

Authentication controllers handle signup (with bcryptjs password hashing and role linking) and signin (with password verification and JWT issuance). User controllers expose endpoints for public and protected data, with access restricted based on user roles.

Key routes include:

  • /api/auth/signup and /api/auth/signin for registration and login
  • /api/test/all, /api/test/user, /api/test/mod, /api/test/admin for testing user, moderator and admin permissions

Securing Your Node.js Backend: Best Practices

  • Secrets Management: Store sensitive data (JWT secret, DB credentials) in environment variables using packages like dotenv.
  • Token Expiry: Set JWT expirations and consider refresh tokens for session continuity.
  • Secure HTTP Headers: Apply helmet middleware for added protection.
  • Input Validation: Prevent injection by validating requests (consider express-validator).

Running and Testing the API

Start the server with an npm script and use tools like Postman to test endpoint authentication. Sign up users, sign in and attach JWT tokens to requests for protected resources. Role-based restrictions ensure only authorized users can access critical endpoints.


Conclusion and Next Steps

This setup provides a solid starting point for a secure Node.js API with JWT authentication and role-based access using MySQL. For further enhancements, like refresh tokens, integrating with frontend frameworks, or production deployment, see the full tutorial for in-depth examples and advanced topics.

Find out more on the complete JWT authentication guide for Node.js, Express.js and MySQL here: https://www.corbado.com/blog/nodejs-express-mysql-jwt-authentication-roles

Top comments (0)