Setting Up a Node.js Development Environment with MySQL, Sequelize, and TypeScript
Punam Pudasaini
Posted on November 29, 2024
Why Node.js with MySQL and Sequelize?
Node.js is a powerful backend technology, and MySQL remains a popular relational database for many applications. Pairing it with Sequelize ORM simplifies database interactions, and TypeScript ensures type safety, improving developer productivity and reducing bugs.
Now, let's get hands-on.
Getting Started
Step 1: Setting Up the Project
mkdir node-mysql-sequelize-ts
cd node-mysql-sequelize-ts
npm init -y
Step 2: Install Dependencies
Install the required packages:
npm install express sequelize mysql2
npm install --save-dev typescript @types/node @types/express ts-node nodemon
Step 3: Configure TypeScript
Generate a tsconfig.json:
tsc --init
Update the configuration:
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
}
}
Step 4: Setting Up Sequelize
Create a src/config/database.ts file:
import { Sequelize } from "sequelize";
const sequelize = new Sequelize("database_name", "username", "password", {
host: "localhost",
dialect: "mysql",
});
export default sequelize;
Step 5: Model Definition
Create src/models/User.ts:
import { DataTypes, Model } from "sequelize";
import sequelize from "../config/database";
class User extends Model {}
User.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
},
{
sequelize,
tableName: "users",
}
);
export default User;
Step 6: Connecting Sequelize with the App
Database Sync
In src/index.ts, synchronize Sequelize models:
import sequelize from "./config/database";
import User from "./models/User";
const start = async () => {
try {
await sequelize.sync({ force: true }); // Creates tables
console.log("Database synchronized!");
} catch (error) {
console.error("Error syncing database:", error);
}
};
start();
*Step 6: Testing the Setup *
Add a Basic Route
Update src/index.ts to include a test route:
import express, { Request, Response } from "express";
import sequelize from "./config/database";
import User from "./models/User";
const app = express();
const port = 3000;
app.get("/", async (req: Request, res: Response) => {
try {
const users = await User.findAll();
res.json(users);
} catch (error) {
res.status(500).send("Database error");
}
});
app.listen(port, async () => {
console.log(`Server running on http://localhost:${port}`);
await sequelize.authenticate();
});
Start the development server:
npm run dev
💖 💪 🙅 🚩
Punam Pudasaini
Posted on November 29, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.