Step 1: Project Setup
- Initialize the ProjectFirst, create a new directory for your project and initialize it with npm:
mkdir express-backend-boilerplate
cd express-backend-boilerplate
npm init -y
Install Dependencies
Install the necessary dependencies for the project:
npm install express reflect-metadata
npm install --save-dev nodemon
npm install typeorm -D
// For Mysql
npm install mysql2
// for sqlite
npm install sqlite3
- express: The web framework for building the API.
- typeorm: ORM for interacting with the database.
- mysql2: MySQL driver.
- reflect-metadata: Used by TypeORM for decorators.
- nodemon: Automatically restarts the server when file changes are detected.
Setup Scripts in package.json
Update the scripts
section in your package.json
to include a start script with nodemon
:
"scripts": {
"start": "nodemon src/index.js"
}
Create the Project Structure
Organize the project with the following directory structure:
express-backend-boilerplate/
├── src/
│ ├── config/
│ │ └── ormconfig.js // Database configuration
│ ├── index.js // Entry point
│ ├── modules/
│ │ └── student/ // Student module
│ │ ├── controllers/
│ │ ├── entities/
│ │ ├── routes/
│ │ ├── services/
│ │ └── studentModule.js // Student module initialization
├── .env // Environment variables
└── package.json
Step 2: Configure the Database
- Create
ormconfig.js
In thesrc/config/
directory, create aormconfig.js
file to define the database configuration:
module.exports = {
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'your_password',
database: 'your_database_name',
entities: ['src/modules/**/entities/*.js'], // Ensure this path is correct for your entity files
migrations: ['src/migrations/*.js'], // Ensure this path is correct for your migration files
cli: {
migrationsDir: 'src/migrations', // Directory where new migrations will be generated
},
synchronize: false, // Turn off synchronization when using migrations
logging: true, // Enable logging for debugging (optional)
};
for sqlite3
module.exports = {
type: 'sqlite',
database: 'database.sqlite', // SQLite database file
entities: ['src/modules/**/*.js'], // Auto-load entities from modules
migrations: ['src/migrations/*.js'], // Specify the migrations directory
cli: {
migrationsDir: 'src/migrations', // Directory where new migrations will be generated
},
synchronize: false, // Turn off synchronization when using migrations
logging: true, // Enable logging for debugging (optional)
};
- synchronize: true will automatically sync your database schema with your entities. Set this to
false
in production.
Setup .env
File
Create a .env
file in the root of the project for environment variables:
touch .env
Add your database credentials:
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=root
DB_PASSWORD=password
DB_NAME=express_backend_boilerplate
Step 3: Initialize the Application
- Setup
index.js
Create the entry pointindex.js
in thesrc/
directory:
require('dotenv').config(); // Load environment variables
require('reflect-metadata'); // Required by TypeORM for decorators
const express = require('express');
const { DataSource } = require('typeorm');
const ormConfig = require('./config/ormconfig');
// Initialize TypeORM DataSource
const AppDataSource = new DataSource(ormConfig);
const initializeApp = async () => {
// Initialize DataSource
await AppDataSource.initialize();
console.log('Database connected successfully!');
// Initialize Express app
const app = express();
// Configure middlewares
app.use(express.json());
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
};
initializeApp().catch((error) => {
console.error('Error initializing app:', error);
});
// Export the AppDataSource for TypeORM CLI usage
module.exports = {
AppDataSource,
};
AppDataSource: This is the TypeORM DataSource instance, initialized with our ormconfig.js
.
studentModule.routes: Here, we’re going to import the routes from our Student module and mount them on the /api/students
path.
Generate the Migration
Now that your AppDataSource
is exported, you can run the migration generation command again:
npx typeorm migration:generate src/migrations/database-initial -d src/index.js -o
Apply the Migration
If the migration is generated successfully, apply it using:
npx typeorm migration:run -d src/index.js
Run the Project
Now that the libraries are installed, you can proceed to run your project with:
npm start