Lesson 21 / 30

TypeORM with Fastify

Integrate TypeORM for type-safe database access.

Why TypeORM?

TypeORM provides type-safe queries, migrations, and relations. Pair it with Fastify for a robust, scalable backend.

Setting up TypeORM

Initialize a data source and create a plugin to manage the connection.

import { DataSource } from 'typeorm';
import { User } from './entities/User.js';

const AppDataSource = new DataSource({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  database: 'mydb',
  entities: [User],
  synchronize: true,
});

export default async function typeormPlugin(fastify) {
  await AppDataSource.initialize();
  fastify.decorate('db', AppDataSource);
  
  fastify.addHook('onClose', () => AppDataSource.destroy());
}