Skip to content

A production-ready NestJS boilerplate with Sequelize ORM, email service, and complete user authentication system. Jumpstart your backend development with pre-configured modules for building robust APIs.

License

Notifications You must be signed in to change notification settings

sofiatechnology/nestjs-sequelize-starter

Repository files navigation

πŸš€ NestJS Sequelize Starter

License: MIT NestJS Sequelize TypeScript

A production-ready NestJS boilerplate with Sequelize ORM, email service, and complete user authentication system.

Jumpstart your backend development with pre-configured modules for building robust APIs.

Features β€’ Quick Start β€’ Documentation β€’ API Endpoints


✨ Features

  • πŸš€ NestJS Framework - Progressive Node.js framework for efficient server-side applications
  • πŸ—„οΈ Sequelize ORM - Full-featured ORM with PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL support
  • πŸ” Multiple Authentication Methods
    • JWT-based authentication
    • Google OAuth 2.0 integration
    • OTP (One-Time Password) login - Passwordless authentication via email
  • πŸ“§ Email Service - Professional SMTP email service with HTML templates
    • Login notifications with IP tracking
    • OTP delivery with styled templates
    • Async email sending
  • πŸ‘€ User Management - Complete user model with UUID primary keys
  • ⚑ TypeScript - Full TypeScript support for enhanced developer experience
  • πŸ”§ Database Migrations - Sequelize CLI integration for schema management
  • πŸ“ Validation - Built-in request validation with class-validator
  • 🌐 Environment Configuration - Dotenv-based configuration management
  • πŸ›‘οΈ Security - JWT tokens, secure headers, and OTP expiration

πŸ“‹ Table of Contents

Click to expand

πŸš€ Quick Start

Prerequisites

  • Node.js (v18 or higher)
  • npm or yarn
  • Database: PostgreSQL, MySQL, MariaDB, SQLite, or MSSQL
  • Git

Installation

  1. Clone the repository:
git clone https://github.com/sofiatechnology/nestjs-sequelize-starter.git
cd nestjs-sequelize-starter
  1. Install dependencies:
npm install
  1. Set up environment variables:
cp .env-example .env
  1. Configure your .env file (see Configuration)

  2. Run database migrations (in development):

npm run start:dev
# Sequelize will auto-sync the schema in development mode
  1. Start the application:
# Development mode with hot reload
npm run start:dev

# Production mode
npm run build
npm run start:prod

The API will be available at http://localhost:3000


βš™οΈ Configuration

Create a .env file in the root directory with the following variables:

# Database Configuration
DB_HOST=localhost
DB_PORT=5432                    # 5432 for PostgreSQL, 3306 for MySQL
DB_USERNAME=postgres
DB_PASSWORD=your_password
DB_DATABASE=nestjs_sequelize_starter

# Application Configuration
NODE_ENV=development            # development | production | test
PORT=3000
APP_NAME=Your App Name
APP_URL=http://localhost:3000

# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# Google OAuth 2.0
GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback

# Email Configuration (SMTP)
SMTP_HOST=smtp.gmail.com        # or your SMTP provider
SMTP_PORT=587
SMTP_SECURE=false               # true for port 465, false for other ports
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password     # Use app-specific password for Gmail
SMTP_FROM=noreply@yourapp.com

Getting Google OAuth Credentials

  1. Go to Google Cloud Console
  2. Create a new project or select existing one
  3. Enable Google+ API
  4. Go to Credentials β†’ Create Credentials β†’ OAuth 2.0 Client ID
  5. Add authorized redirect URI: http://localhost:3000/auth/google/callback
  6. Copy Client ID and Client Secret to your .env file

Gmail SMTP Setup

For Gmail, you need to use an App Password:

  1. Enable 2-Factor Authentication on your Google account
  2. Go to App Passwords
  3. Generate a new app password for "Mail"
  4. Use this password in SMTP_PASS

πŸ—„οΈ Database Setup

Supported Databases

This starter supports multiple databases through Sequelize:

  • PostgreSQL (recommended)
  • MySQL
  • MariaDB
  • SQLite
  • Microsoft SQL Server

Database Migration

In development, Sequelize will automatically sync your models:

// Database auto-syncs on startup in development
await sequelize.sync({ alter: true });

For production, create proper migrations:

-- Add OTP columns to users table
ALTER TABLE users 
ADD COLUMN otp VARCHAR(255) NULL,
ADD COLUMN otpExpiry TIMESTAMP NULL;

Database Schema

Users Table:

CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  email VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255) NOT NULL,
  googleId VARCHAR(255) NULL,
  otp VARCHAR(255) NULL,
  otpExpiry TIMESTAMP NULL,
  createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

πŸ” Authentication

This starter provides three authentication methods:

1. Google OAuth 2.0

Flow:

  1. User clicks "Login with Google"
  2. Redirects to Google consent screen
  3. Google redirects back with user info
  4. Server creates/finds user and returns JWT token

Endpoints:

  • GET /auth/google - Initiates Google OAuth flow
  • GET /auth/google/callback - Google callback handler

2. OTP (One-Time Password) Login

Flow:

  1. User requests OTP with email
  2. System validates email exists (returns 404 if not)
  3. 6-digit OTP sent via email (valid for 10 minutes)
  4. User submits OTP
  5. System validates and returns JWT token

Endpoints:

  • POST /auth/otp/send - Request OTP
  • POST /auth/otp/verify - Verify OTP and login

3. JWT Token Authentication

All authenticated endpoints require JWT token in Authorization header:

Authorization: Bearer <your-jwt-token>

πŸ“‘ API Endpoints

Authentication Endpoints

πŸ”Ή Google OAuth Login

GET /auth/google

Description: Initiates Google OAuth flow. Redirects to Google consent screen.


πŸ”Ή Google OAuth Callback

GET /auth/google/callback

Description: Handles Google OAuth callback. Returns JWT token and user info.

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "user@example.com",
    "name": "John Doe"
  }
}

πŸ”Ή Request OTP

POST /auth/otp/send
Content-Type: application/json

{
  "email": "user@example.com"
}

Success Response (200):

{
  "message": "OTP sent successfully"
}

Error Response (404):

{
  "statusCode": 404,
  "message": "Email not found"
}

πŸ”Ή Verify OTP

POST /auth/otp/verify
Content-Type: application/json

{
  "email": "user@example.com",
  "otp": "123456"
}

Success Response (200):

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "user@example.com",
    "name": "John Doe"
  }
}

Error Responses:

  • 404 - Email not found
  • 401 - Invalid OTP
  • 401 - OTP expired (10 minutes)
  • 401 - No OTP found (request new one)

πŸ”Ή Get User Profile

GET /auth/profile
Authorization: Bearer <jwt-token>

Response:

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "user@example.com",
  "name": "John Doe"
}

πŸ“§ Email Templates

The starter includes professional HTML email templates:

1. OTP Email Template

  • Clean, modern design
  • Large, easy-to-read OTP code
  • 10-minute expiration warning
  • Mobile-responsive

2. Login Notification Email

  • IP address tracking
  • Timestamp of login
  • Security alert styling
  • Links to account security

Customizing Email Templates

Email templates are located in src/email/email.service.ts:

private getOTPTemplate(name: string, appName: string, otp: string, appUrl: string): string {
  // Customize HTML template here
}

πŸ“ Project Structure

nestjs-sequelize-starter/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ auth/                      # Authentication module
β”‚   β”‚   β”œβ”€β”€ guards/                # Auth guards (JWT, Google)
β”‚   β”‚   β”œβ”€β”€ auth.controller.ts     # Auth endpoints
β”‚   β”‚   β”œβ”€β”€ auth.service.ts        # Auth business logic
β”‚   β”‚   β”œβ”€β”€ auth.module.ts         # Auth module definition
β”‚   β”‚   β”œβ”€β”€ jwt.strategy.ts        # JWT strategy
β”‚   β”‚   └── google.strategy.ts     # Google OAuth strategy
β”‚   β”œβ”€β”€ email/                     # Email service module
β”‚   β”‚   β”œβ”€β”€ email.service.ts       # Email sending & templates
β”‚   β”‚   └── email.module.ts        # Email module definition
β”‚   β”œβ”€β”€ models/                    # Database models
β”‚   β”‚   └── user.model.ts          # User model (Sequelize)
β”‚   β”œβ”€β”€ app.module.ts              # Root application module
β”‚   └── main.ts                    # Application entry point
β”œβ”€β”€ .env-example                   # Environment variables template
β”œβ”€β”€ .gitignore                     # Git ignore rules
β”œβ”€β”€ package.json                   # Dependencies & scripts
β”œβ”€β”€ tsconfig.json                  # TypeScript configuration
└── README.md                      # This file

πŸ› οΈ Development

Available Scripts

# Development mode with hot reload
npm run start:dev

# Production build
npm run build

# Production mode
npm run start:prod

# Run tests
npm run test

# Run e2e tests
npm run test:e2e

# Test coverage
npm run test:cov

# Lint code
npm run lint

# Format code
npm run format

Adding New Features

  1. Create a new module:
nest generate module feature-name
nest generate controller feature-name
nest generate service feature-name
  1. Create database model:
// src/models/feature.model.ts
import { Table, Column, Model, DataType } from 'sequelize-typescript';

@Table({ tableName: 'features' })
export class Feature extends Model {
  @Column({ type: DataType.UUID, primaryKey: true })
  id: string;
  
  // Add your columns here
}
  1. Register model in module:
import { SequelizeModule } from '@nestjs/sequelize';
import { Feature } from '../models/feature.model';

@Module({
  imports: [SequelizeModule.forFeature([Feature])],
  // ...
})

πŸš€ Deployment

Environment Variables

Ensure all production environment variables are set:

  • Use strong JWT_SECRET (minimum 32 characters)
  • Set NODE_ENV=production
  • Use production database credentials
  • Configure production APP_URL

Database Migration

Run migrations before deploying:

-- Production migration script
ALTER TABLE users 
ADD COLUMN IF NOT EXISTS otp VARCHAR(255),
ADD COLUMN IF NOT EXISTS otpExpiry TIMESTAMP;

Deployment Platforms

Recommended platforms:

Docker Deployment

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "run", "start:prod"]

πŸ§ͺ Testing

Testing OTP Flow

# 1. Request OTP
curl -X POST http://localhost:3000/auth/otp/send \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com"}'

# 2. Check email for OTP code

# 3. Verify OTP
curl -X POST http://localhost:3000/auth/otp/verify \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "otp": "123456"}'

# 4. Use JWT token
curl http://localhost:3000/auth/profile \
  -H "Authorization: Bearer <your-jwt-token>"

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • NestJS - The progressive Node.js framework
  • Sequelize - Promise-based ORM for Node.js
  • Passport - Authentication middleware

πŸ“ž Support


Built with ❀️ using NestJS and TypeScript

About

A production-ready NestJS boilerplate with Sequelize ORM, email service, and complete user authentication system. Jumpstart your backend development with pre-configured modules for building robust APIs.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published