How to Use Sequelize with Express: Simple Setup and Example
To use
Sequelize with Express, first install Sequelize and a database driver, then create a Sequelize instance to connect your database. Use Sequelize models to define tables and integrate them in Express routes to handle data operations.Syntax
Here is the basic syntax to set up Sequelize with Express:
- Import Sequelize: Load Sequelize library.
- Create Sequelize instance: Connect to your database with credentials.
- Define models: Describe your database tables as JavaScript classes.
- Use models in routes: Perform database operations inside Express route handlers.
javascript
import express from 'express'; import { Sequelize, DataTypes } from 'sequelize'; const app = express(); app.use(express.json()); // Create Sequelize instance const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'postgres', // or 'mysql', 'sqlite', etc. }); // Define a model const User = sequelize.define('User', { name: { type: DataTypes.STRING, allowNull: false }, email: { type: DataTypes.STRING, unique: true, allowNull: false } }); // Express route example app.get('/users', async (req, res) => { const users = await User.findAll(); res.json(users); });
Example
This example shows a simple Express server using Sequelize to connect to a SQLite database, define a User model, sync the database, and provide a route to get all users.
javascript
import express from 'express'; import { Sequelize, DataTypes } from 'sequelize'; const app = express(); app.use(express.json()); // Connect to SQLite database const sequelize = new Sequelize({ dialect: 'sqlite', storage: './database.sqlite' }); // Define User model const User = sequelize.define('User', { name: { type: DataTypes.STRING, allowNull: false }, email: { type: DataTypes.STRING, unique: true, allowNull: false } }); // Sync database and start server (async () => { await sequelize.sync({ force: true }); // Creates tables // Create sample user await User.create({ name: 'Alice', email: 'alice@example.com' }); app.get('/users', async (req, res) => { const users = await User.findAll(); res.json(users); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); })();
Output
Server running on http://localhost:3000
// When visiting http://localhost:3000/users
[
{
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"createdAt": "2024-06-01T00:00:00.000Z",
"updatedAt": "2024-06-01T00:00:00.000Z"
}
]
Common Pitfalls
Common mistakes when using Sequelize with Express include:
- Not awaiting asynchronous Sequelize calls, causing unexpected behavior.
- Forgetting to sync the database before querying models.
- Not handling errors in async routes, which can crash the server.
- Using incorrect database credentials or dialect causing connection failures.
Always use try/catch blocks or middleware to handle errors gracefully.
javascript
app.get('/users', async (req, res) => { // Wrong: missing await const users = User.findAll(); res.json(users); // Sends a Promise, not data }); // Correct way app.get('/users', async (req, res) => { try { const users = await User.findAll(); res.json(users); } catch (error) { res.status(500).json({ error: 'Failed to fetch users' }); } });
Quick Reference
Tips for using Sequelize with Express:
- Always await Sequelize async calls.
- Use
sequelize.sync()to create tables before queries. - Handle errors with
try/catchin async routes. - Define models clearly with data types and constraints.
- Use environment variables for database credentials.
Key Takeaways
Create a Sequelize instance with your database info before using models.
Define models to represent your database tables clearly.
Always await Sequelize calls inside async Express routes.
Sync your database before running queries to ensure tables exist.
Handle errors in routes to keep your server stable.