Logo

dev-resources.site

for different kinds of informations.

Getting Started with Prisma, SQLite, and Express

Published at
11/30/2024
Categories
prisma
backend
fullstack
development
Author
lachiamine
Author
10 person written this
lachiamine
open
Getting Started with Prisma, SQLite, and Express

Prisma is a modern ORM that simplifies database management for Node.js and TypeScript projects. In this guide, we’ll explore how to set up Prisma with SQLite and integrate it into an Express application.

Why Prisma?

Prisma offers:

Type-safe queries: Automatically generated types for your database schema.
Ease of setup:Works seamlessly with many databases, including SQLite.
Developer-friendly tooling: Includes a powerful migration system and intuitive query APIs.

Prerequisites
Before diving in, ensure you have the following installed:

Node.js (LTS recommended)
npm or yarn

Initialize Your Project
Start by creating a new Node.js project:

mkdir prisma-express-app  
cd prisma-express-app  
npm init -y 
Enter fullscreen mode Exit fullscreen mode

Install Dependencies
Install the necessary packages for Prisma, SQLite, and Express:

npm install express sqlite3  
npm install @prisma/client  
npm install -D prisma
Enter fullscreen mode Exit fullscreen mode

Initialize Prisma
Run the following command to set up Prisma:

npx prisma init
Enter fullscreen mode Exit fullscreen mode

This creates
A prisma/schema.prisma file to define your database schema.
A .env file for environment variables.

Configure SQLite
Update the .env file with the path to your SQLite database:

DATABASE_URL="file:./dev.db"
Enter fullscreen mode Exit fullscreen mode

Update the prisma/schema.prisma file to use SQLite:

generator client {  
  provider = "prisma-client-js"  
}  

datasource db {  
  provider = "sqlite"  
  url      = env("DATABASE_URL")  
}  

model User {  
  id    Int     @id @default(autoincrement())  
  name  String  
  email String  @unique  
}  
Enter fullscreen mode Exit fullscreen mode

Here, we’ve defined a simple User model.

Run Migrations
Generate the SQLite database and apply the schema:

npx prisma migrate dev --name init  
This creates the dev.db SQLite file and applies your schema
Enter fullscreen mode Exit fullscreen mode

.

Generate Prisma Client
Run the following command to generate the Prisma client:

npx prisma generate
Enter fullscreen mode Exit fullscreen mode

Create an Express App
Set up an Express server and integrate Prisma:

const express = require('express');  
const { PrismaClient } = require('@prisma/client');  

const prisma = new PrismaClient();  
const app = express();  

app.use(express.json());  

// Create a user  
app.post('/users', async (req, res) => {  
  const { name, email } = req.body;  
  try {  
    const user = await prisma.user.create({ data: { name, email } });  
    res.status(201).json(user);  
  } catch (error) {  
    res.status(400).json({ error: error.message });  
  }  
});  

// Get all users  
app.get('/users', async (req, res) => {  
  const users = await prisma.user.findMany();  
  res.json(users);  
});  

const PORT = process.env.PORT || 3000;  
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`)); 
Enter fullscreen mode Exit fullscreen mode

Test Your API
Start your server:

node index.js
Enter fullscreen mode Exit fullscreen mode

Use tools like Postman or cURL to test the endpoints:

POST /users to create a new user.
GET /users to retrieve all users.
Enter fullscreen mode Exit fullscreen mode

Explore Prisma Studio
Prisma Studio is a GUI for managing your database. Run:

npx prisma studio
Enter fullscreen mode Exit fullscreen mode

Access it at http://localhost:5555.

Conclusion
You’ve now set up Prisma with SQLite and integrated it into an Express app! Prisma simplifies database management and gives you a clean, type-safe interface for working with your data.

If you want to dive deeper, check out the official Prisma documentation.

its just written by 0xapma

prisma Article's
30 articles in total
Favicon
How to Fix the “Record to Delete Does Not Exist” Error in Prisma
Favicon
Building Type-Safe APIs: Integrating NestJS with Prisma and TypeScript
Favicon
Deploying an Existing Express API + Prisma + Supabase Project to Vercel
Favicon
Exploring the Power of Full-Stack Development with Next.js and Prisma
Favicon
How to integrate GitHub CopilotKit with Prisma Integration into your nextJs project Using OpenAI
Favicon
วิธีทำ Auth API ด้วย Express, JWT, MySQL และ Prisma
Favicon
Prisma
Favicon
How we built "Space-Ease" using Next.js
Favicon
Query Objects Instead of Repositories: A Modern Approach to Data Access
Favicon
Common Data Loss Scenarios & Solutions in Prisma Schema Changes
Favicon
How I Solved Common Prisma ORM Errors: Debugging Tips and Best Practices
Favicon
Prisma 101 baby.
Favicon
Prisma
Favicon
QueryBuilder in Action Part 1
Favicon
Prisma ORM: Revolutionizing Database Interactions
Favicon
Prisma & MongoDB: server to be run as a replica set
Favicon
Using GenAI to Tackle Complex Prisma Model Migrations
Favicon
When Embedded AuthN Meets Embedded AuthZ - Building Multi-Tenant Apps With Better-Auth and ZenStack
Favicon
Building Multi-Tenant Apps Using StackAuth's "Teams" and Next.js
Favicon
The Most Awaited Prisma Course Is Here! 😍
Favicon
**Building a Full-Stack Next.js Starter Kit: Authentication, GraphQL, and Testing**
Favicon
Integrate DAYTONA and let the magic begin....
Favicon
Cloudflare D1 and Prisma: Not a Good Combination (For Now)
Favicon
Resolving the `DO $$` Issue in Drizzle ORM with Nile Postgres
Favicon
Nuxt Authorization: How to Implement Team Role-Based Access Control in Nuxt 3
Favicon
Getting Started with Prisma, SQLite, and Express
Favicon
Senior Developer Advocate
Favicon
Building Multi-Tenant Apps Using Clerk's "Organization" and Next.js
Favicon
How to use ORMs (Prisma / Drizzle / Knex.js) in a TypeScript backend built with Encore.ts
Favicon
Pagination and Sorting with Prisma in TypeScript

Featured ones: