NextJs + Drizzle + Neon CRUD app
What is CRUD?
CRUD basically stands for (C)reate, (R)ead, (U)pdate, (D)elete.
๐งบ Imagine you have a fruit basket.
๐ You put an apple in it (Create).
๐ You look inside to see what fruits you have (Read).
๐ You change the apple for a banana (Update).
๐๏ธ You take out the banana and throw it away (Delete).
Why is CRUD important?
CRUD is the backbone of almost every app you use daily.
๐ฑ On Instagram, you post a photo (Create), view your feed (Read), edit your caption (Update), or delete a photo (Delete).
๐ In a Notes app, you add, view, edit, or remove notes.
๐ต In Spotify, adding a song to your playlist, viewing playlists, renaming them, or removing songs are all CRUD operations.
Without CRUD, your app would be static and useless. Users need to add data, view it, change it, and remove it for your app to be interactive and useful.
Understanding CRUD helps you see how your frontend, backend, and database connect together to make your app work.
A simple CRUD app
Heres how you build a simple CRUD app using NextJs + DrizzleORM + NeonDB
- Initialize NextJs app and ShadCN
# nextjs
pnpm dlx create-next-app@latest
# shadcn
pnpm dlx shadcn@latest init
- Setting Up DrizzleORM and NeonDB
# drizzle
pnpm add drizzle-orm
pnpm add -D drizzle-kit\
# neon
pnpm add @neondatabase/serverless
# dotenv
pnpm add dotenv
- Put the connection string to
.env
Visit Neon Projects to get your connection string.
# .env
DATABASE_URL=your_neon_database_string_here
- Create
drizzle.ts
// src/db/drizzle.ts
import { drizzle } from "drizzle-orm/neon-http";
export const db = drizzle(process.env.DATABASE_URL);
- Create
schema.ts
// src/db/schema.ts
import { pgTable, text, timeStamp, uuid } from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: uuid("id").primaryKey().defaultRandom(),
email: text("email").notNull().unique(),
username: text("username").notNull().unique(),
password: text("password").notNull(),
createdAt: timeStamp("created_at").defaultNow(),
updatedAt: timeStamp("updated_at"). defaultNow(),
});
export type User = typeof users.$inferSelect;
- Create
drizzle.config.ts
import { defineConfig } from "drizzle-kit";
export default defineConfig({
schema: "./src/db/schema.ts",
out: "./migrations",
dialect: "postgresql",
dbCredentials: {
url: process.env.DATABASE_URL!,
}
});
- Pushing schemas to DB
pnpm dlx drizzle-kit push