Skip to content

Step 9 - Databases!

Course: NextJS (Server side) - chapter 9

We have a bunch of dummy routes, we need to add a database layer to persist data.

Adding prisma to a Next.js project is straightforward.

💡 Please get a free Postgres DB from either neon or aiven

  1. Install prisma
npm install prisma
  1. Initialize prisma schema
npx prisma init
  1. Create a simple user schema
model User {
id Int @id @default(autoincrement())
username String @unique
password String
}
  1. Replace .env with your own Postgres URL
DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
  1. Migrate the database
npx prisma migrate dev --name init_schema
  1. Generate the client
npx prisma generate
  1. Finish the signup route
export async function POST(req: NextRequest) {
const body = await req.json();
// should add zod validation here
const user = await client.user.create({
data: {
username: body.username,
password: body.password
}
});
console.log(user.id);
return NextResponse.json({ message: "Signed up" });
}
  1. Update the GET endpoint
export async function GET() {
const user = await client.user.findFirst({});
return Response.json({ name: user?.username, email: user?.username })
}

💡 We’re not doing any authentication yet. Which is why we’re not returning a jwt (or setting a cookie) here