Chapter 52: Node.js MySQL

MySQL with Node.js — explained as if I’m sitting next to you right now, building a real project together.

We will go step by step, slowly, with lots of reasoning, copy-paste-ready code, common beginner traps, intermediate mistakes, production-grade patterns and 2025–2026 best practices.

Goal of this tutorial

We will build a realistic Task Management REST API that uses MySQL as the database, including:

  • User registration & login (JWT)
  • CRUD operations on personal tasks
  • Input validation (Zod)
  • Proper error handling
  • Connection pooling
  • Environment variables + validation
  • Logging
  • Security headers
  • TypeScript + ESM

This is the kind of foundation many real Node.js backends use today.

Step 1 – Project setup (modern & realistic)

Bash

tsconfig.json (strict & modern)

JSON

package.json scripts

JSON

Step 2 – Folder structure (what most real teams use)

text

Step 3 – Database connection with mysql2 (pooling – production must-have)

src/config/database.ts

TypeScript

.env.example (give this to your team)

text

Important security note

  • Never commit .env
  • Use secret managers (AWS Secrets Manager, Doppler, Infisical, 1Password, HashiCorp Vault) in production
  • Use connection pooling (10–30 connections) — never create new connection per request

Step 4 – First real database table (manual SQL – no ORM yet)

Run this in MySQL (via MySQL Workbench, DBeaver, phpMyAdmin, or terminal)

SQL

Why manual SQL here?

  • You understand exactly what is happening
  • No magic → easier to debug
  • Later we can switch to Prisma/Drizzle without rewriting logic

Step 5 – User registration & login (real production style)

src/controllers/auth.controller.ts

TypeScript

Step 6 – Protected route middleware

src/middleware/auth.middleware.ts

TypeScript

Step 7 – Task CRUD with MySQL

src/controllers/task.controller.ts

TypeScript

Summary – MySQL + Node.js in 2025–2026 feels like this

You now have:

  • Connection pooling (mysql2/promise)
  • Type-safe environment variables (Zod)
  • Custom errors + global handler
  • JWT authentication
  • Secure password hashing (bcrypt)
  • Raw SQL queries with prepared statements
  • Input validation
  • Security headers & compression

This is very close to what many real Node.js backends look like today (with Prisma/Drizzle added later for convenience).

Which direction would you like to go next?

  • Add Prisma instead of raw SQL (most popular choice)
  • Add Drizzle ORM (type-safe SQL – very fast growing)
  • Implement refresh tokens + cookie-based auth
  • Add pagination, filtering, sorting for tasks
  • Add unit & integration tests with Vitest
  • Docker + production deployment checklist

Just tell me what you want to build or understand next — I’ll continue with complete, secure, production-ready code. 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *