Nuxt 3 Layers: Building a SaaS Factory - Database Layer with Drizzle
last week - 11 min read •In the previous article, we explored how to create a UI layer for a Nuxt 3 SaaS project. Now, in part two of this series, we’ll focus on building a database layer using Drizzle. Unlike the UI layer, this won’t be a Nuxt 3 layer but rather a standalone npm package.
Setting Up the Database Layer
We will create a simple package named @jiprochazka/db, which will encapsulate our database logic using Drizzle ORM and Postgres.
Step1: Define package.json
$ cd packages
$ mkdir db
Create package.json
:
// packages/db/package.json
{
"name": "@jiprochazka/db",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"dev": "tsc --watch"
}
Step1: Install Dependencies
Install the necessary dependencies within the db
folder. Run the following command:
$ pnpm add dotenv drizzle-orm postgres
For development dependencies, install:
$ pnpm add -D @types/node drizzle-kit tsx typescript
Step 2: Configure TypeScript
Create a tsconfig.json file to configure TypeScript:
// packages/db/tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"types": ["node"],
"moduleResolution": "node",
"resolveJsonModule": true,
"allowJs": true
},
"include": ["src", "*.ts"],
"exclude": ["node_modules", "dist"]
}
Step 3: Implement the Database Connection
In the src
directory, create an index.ts
file with the following content:
// packages/db/src/index.ts
import postgres from "postgres";
import { drizzle } from "drizzle-orm/postgres-js";
export const client = postgres(process.env.DATABASE_URL!);
export const db = drizzle(client);
Explanation:
- We use postgres from postgres to establish a database connection.
- drizzle wraps the Postgres client, providing ORM functionality.
- The database URL is retrieved from environment variables.
Using the Layer
In the project app, add the npm package to the app package.json
:
// apps/my-app/package.json
"dependencies": {
...
"~db": "workspace:@jiprochazka/db@*",
}
Now you are ready and the usage is simple (after setting the environment variable, of course):
import { db } from "~db"
const result = await db.select().from(users);
Summary
In this article, we created a standalone npm package for our database layer using Drizzle ORM and Postgres. This package can now be imported and used in any part of our SaaS platform, making the database logic modular and reusable.
Stay tuned!