Learn Next.js · 14/15

Database Integration: The Full Stack Completes

12 min read

Database Integration: The Full Stack Completes 🚀

Welcome back! So far, we've been building the front-end of our Next.js application, which is like designing a beautiful and functional storefront. But what's a store without any products on the shelves? To make our application truly dynamic and interactive, we need to connect it to a database. This is where the "full stack" part of Next.js really shines, allowing us to manage both the client-side and the server-side, including our data.

Think of it like this: our Next.js front-end is the friendly cashier and the beautifully arranged displays in a bookstore. The database is the massive, organized warehouse in the back where all the books are stored. We need a system to allow the cashier to request a specific book from the warehouse and bring it to the customer. That system is what we're going to build.


Choosing an ORM: Prisma vs Drizzle Overview 🧰

What's an ORM and Why Do I Need One?

Before we start slinging data around, let's talk about how we "talk" to our database. Databases, like PostgreSQL, speak a language called SQL (Structured Query Language). You could write raw SQL queries in your Next.js application, but that can get messy and error-prone very quickly.

Imagine you're an English-speaking chef in a kitchen where all the recipe books are in French. You could try to learn French on the fly, but you're likely to mistake "salt" for "sugar" at some point. An ORM (Object-Relational Mapper) is like having a fluent translator by your side. You tell the translator in your native language (in our case, JavaScript or TypeScript), "I need the recipe for a chocolate cake," and the translator perfectly communicates that to the French recipe book and brings you the correct instructions.

An ORM allows you to interact with your database using the programming language you're already comfortable with, like TypeScript. It maps the tables in your database to objects in your code, making your life significantly easier and your code more readable and maintainable.

Meet the Contenders: Prisma and Drizzle

In the world of Next.js and TypeScript, two popular ORMs have emerged as top choices: Prisma and Drizzle.

Prisma: The All-in-One Toolkit 🛠️

Prisma is a very popular and mature ORM that provides a fantastic developer experience. It comes with its own schema definition language, a powerful query builder, and a type-safe client.

How Prisma Works:

  1. Define your schema: You define your database models in a special schema.prisma file. This file becomes the single source of truth for your database structure.
  2. Generate the client: You run a command, and Prisma generates a highly optimized and type-safe client based on your schema.
  3. Query your data: You use the generated client in your code to interact with your database.

Example: A Simple schema.prisma

prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

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

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Querying with Prisma Client:

typescript
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function getPublishedPosts() {
  const posts = await prisma.post.findMany({
    where: { published: true },
  });
  return posts;
}

Interesting Fact: The team behind Prisma is very focused on developer experience. They even built their own query engine in Rust to ensure high performance!

Drizzle: The Lightweight and Familiar Friend 💧

Drizzle ORM takes a slightly different approach. It aims to be more lightweight and closer to writing actual SQL, but with the full benefits of TypeScript's type safety. If you're already comfortable with SQL, you might find Drizzle very intuitive.

How Drizzle Works:

  1. Define your schema in TypeScript: Instead of a separate schema file, you define your table structures directly in TypeScript files.
  2. Query with a SQL-like syntax: Drizzle's query builder mimics SQL syntax, making it easy to pick up for those with a database background.

Example: Defining a Schema with Drizzle

typescript
import { pgTable, serial, text, boolean, timestamp } from 'drizzle-orm/pg-core';

export const posts = pgTable('posts', {
  id: serial('id').primaryKey(),
  title: text('title').notNull(),
  content: text('content'),
  published: boolean('published').default(false),
  createdAt: timestamp('created_at').defaultNow(),
  updatedAt: timestamp('updated_at').defaultNow(),
});

Querying with Drizzle:

typescript
import { db } from './db'; // Your database connection
import { posts } from './schema';
import { eq } from 'drizzle-orm';

async function getPublishedPosts() {
  const publishedPosts = await db.select().from(posts).where(eq(posts.published, true));
  return publishedPosts;
}

So, Which One Should You Choose?

  • Choose Prisma if: You want a more "all-in-one" solution with a dedicated schema language and a very intuitive query API. It's great for developers who want to abstract away a lot of the SQL complexities.
  • Choose Drizzle if: You prefer to write something that feels closer to SQL and want a more lightweight library. It's excellent for those who appreciate seeing the underlying SQL patterns in their TypeScript code.

For this guide, we'll proceed with Prisma due to its widespread adoption and beginner-friendly nature.


Connecting Next.js to a Cloud Database (e.g., PostgreSQL/Supabase) ☁️

Now that we've chosen our translator (Prisma), we need to connect it to our warehouse (the database). We'll use a cloud database provider to avoid the hassle of setting up and maintaining a database on our own machine. Supabase is a fantastic option because it's built on top of PostgreSQL and provides a generous free tier.

Step 1: Set up a Supabase Project

  1. Go to supabase.com and create an account.
  2. Create a new project. Give it a name and a strong database password. Make sure to save this password somewhere safe!
  3. Choose a region that is geographically close to you and your users for lower latency.
  4. Wait for your project to be provisioned. It's like the construction crew is building your new data warehouse.

Step 2: Get Your Database Connection String

  1. Once your project is ready, navigate to the "Project Settings" (the gear icon).
  2. In the sidebar, click on "Database".
  3. Under "Connection string", you'll find a URI that starts with postgresql://. This is the secret address to your database. Copy it.

Step 3: Install Prisma and the Prisma Client

In your Next.js project's terminal, run the following command:

bash
npm install prisma --save-dev
npm install @prisma/client

Step 4: Initialize Prisma

Now, let's initialize Prisma in our project:

bash
npx prisma init

This command does two things:

  • It creates a prisma directory with a schema.prisma file. This is where we'll define our database models.
  • It creates a .env file at the root of your project. This file is for storing environment variables, like our secret database connection string.

Step 5: Add the Connection String to your .env file

Open the .env file and add your Supabase connection string. Make sure to replace [YOUR-PASSWORD] with the password you saved earlier.

ini
DATABASE_URL="postgresql://postgres:[YOUR-PASSWORD]@db.<your-project-ref>.supabase.co:5432/postgres"

Important: The .env file should never be committed to your version control (like Git). The .gitignore file that comes with Next.js should already have .env listed. This is to prevent your secret database credentials from being exposed to the public. Think of it as not leaving the keys to your warehouse lying on the sidewalk.

Step 6: Define a Model in schema.prisma

Let's go back to the prisma/schema.prisma file and define a simple User model.

prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

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

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}

Step 7: Push Your Schema to the Database

Now, we need to tell Prisma to update our Supabase database to match our schema.

bash
npx prisma db push

This command will inspect your schema.prisma file and make the necessary changes to your cloud database. It will create the User table for us.

Funny Exaggeration: If you forget this step, it's like designing the blueprints for a magnificent bookshelf but never actually sending them to the carpenter. Your app will have no idea where to put the books!

We are now successfully connected to our cloud database! 🤝


Querying the Database Directly from Server Components 🖥️

One of the most powerful features of the Next.js App Router is the ability to use React Server Components. These components run exclusively on the server, which means they can securely and directly interact with our database.

The Old Way vs. The New Way

In the past (with the Pages Router), if you wanted to get data from a database to display on a page, you'd typically have to create a separate API route. Your front-end component would then make a fetch request to that API route, which would then query the database. It's a bit like a game of telephone.

The Server Component Way

With Server Components, we can cut out the middleman. Our component can directly and asynchronously ask the database for the data it needs.

Let's create a Server Component to display a list of users.

1. Create a Prisma Client Instance

It's a good practice to have a single instance of the Prisma Client for your entire application. Create a new file lib/prisma.ts:

typescript
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default prisma;

2. Create the Server Component

Now, let's create a component in app/components/UserList.tsx:

typescript
import prisma from '@/lib/prisma';

export default async function UserList() {
  const users = await prisma.user.findMany();

  return (
    <div>
      <h2 className="text-2xl font-bold mb-4">Users</h2>
      <ul>
        {users.map((user) => (
          <li key={user.id}>
            {user.name} ({user.email})
          </li>
        ))}
      </ul>
    </div>
  );
}

What's Happening Here?

  • This is an async component. This is a key feature of Server Components.
  • We're directly calling prisma.user.findMany() inside the component.
  • Because this component runs on the server, our database credentials are never exposed to the client's browser. It's all happening safely in our server environment.
  • The component will wait for the database query to finish, and only then will it render the HTML and send it to the browser.

Let's Add a User to See it Work

To have some data to display, go to your Supabase dashboard, click on the "Table Editor" in the sidebar, select your User table, and click "Insert row" to add a new user manually.

Now, you can use this UserList component on any of your pages, for example, in app/page.tsx:

typescript
import UserList from '@/app/components/UserList';

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <UserList />
    </main>
  );
}

Run your development server (npm run dev), and you should see the user you added from your database displayed on the page!


Mutating Database Records Securely via Server Actions 🔐

Reading data is great, but what about creating, updating, or deleting it? This is where Server Actions come into play.

The Problem: Secure Data Mutations

How do you let a user on a browser trigger a change in your database without opening up a massive security hole? You can't just trust any request from a client.

Server Actions are functions that you write in your server-side code but can be executed from client-side components. They provide a secure and straightforward way to handle data mutations in Next.js.

Let's Create a Form to Add a New User

We'll create a new component, app/components/AddUserForm.tsx, that will contain a form and a Server Action to handle the submission.

typescript
'use server'; // This directive marks all functions in this file as Server Actions

import prisma from '@/lib/prisma';
import { revalidatePath } from 'next/cache';

export async function addUser(formData: FormData) {
  const name = formData.get('name') as string;
  const email = formData.get('email') as string;

  await prisma.user.create({
    data: {
      name,
      email,
    },
  });

  revalidatePath('/'); // This tells Next.js to re-fetch the data for the home page
}

Breaking Down the Server Action (addUser):

  1. 'use server': This is the magic directive. It tells Next.js that the functions exported from this file are Server Actions and should only be executed on the server.
  2. addUser(formData: FormData): The function takes the form data as an argument.
  3. prisma.user.create(): We use our Prisma client to create a new user in the database.
  4. revalidatePath('/'): This is a very important step. After we add a new user, the user list we displayed on the home page is now out of date. revalidatePath('/') tells Next.js to invalidate its cache for the home page (/) and re-render it with the fresh data from the database. It's like telling the bookstore cashier to go recount the books on a specific shelf because a new shipment just arrived.

Now, let's create the form component in the same file that will use this action:

This will be a client component because it has interactive UI elements.

typescript
// Add this to the top of the file
"use client";

import { useFormStatus } from "react-dom";

// Keep the addUser function from above in this file

function SubmitButton() {
  const { pending } = useFormStatus();

  return (
    <button type="submit" disabled={pending} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
      {pending ? 'Adding...' : 'Add User'}
    </button>
  );
}


export function AddUserForm() {
  return (
    <form action={addUser} className="p-4 border rounded-lg">
      <div className="mb-4">
        <label htmlFor="name" className="block text-sm font-medium text-gray-700">Name</label>
        <input type="text" id="name" name="name" required className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
      </div>
      <div className="mb-4">
        <label htmlFor="email" className="block text-sm font-medium text-gray-700">Email</label>
        <input type="email" id="email" name="email" required className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
      </div>
      <SubmitButton />
    </form>
  );
}

The Form Component (AddUserForm):

  • 'use client': We need this to use hooks like useFormStatus.
  • <form action={addUser}>: This is where the magic happens. We're passing our Server Action addUser directly to the action prop of the form. When the form is submitted, Next.js will securely call this function on the server.
  • SubmitButton: The useFormStatus hook from react-dom gives us the pending state of the form submission. This is great for providing feedback to the user, like disabling the button and showing a "Adding..." message while the server is processing the request.

Now, add <AddUserForm /> to your app/page.tsx. You'll have a form that securely adds a new user to your database, and the user list will automatically update!

Congratulations! You have successfully connected your Next.js application to a database, fetched data using Server Components, and mutated data using Server Actions. Your storefront is now fully connected to your warehouse, creating a complete full-stack experience.


References and Further Reading 📚

Challenge

You are building a simple guestbook application using Next.js and Prisma. Your task is to implement the full data flow: defining the database schema, fetching existing entries, and adding new ones.

You will need to work across four files.

  1. prisma/schema.prisma: Define the database model for a guestbook entry. The model should be named GuestbookEntry and include the following fields:

    • id: An auto-incrementing integer that serves as the primary key.
    • name: A required string for the author's name.
    • message: A required string for the guestbook message.
    • createdAt: A timestamp that defaults to the time of creation.
  2. lib/prisma.ts: To avoid creating too many database connections, create and export a singleton instance of PrismaClient. This instance will be used throughout your application to interact with the database.

  3. app/actions.ts: Create a Server Action to handle form submissions.

    • This file must be marked as a server-only module.
    • Define and export an async function named addEntry that accepts form data as its first argument.
    • Inside the function, extract the name and message fields from the form data.
    • Use your Prisma client instance to create a new GuestbookEntry in the database.
    • After creating the entry, trigger a revalidation of the data on the home page (/).
  4. app/page.tsx: Implement the main page component.

    • This should be an async Server Component.
    • Fetch all existing GuestbookEntry records from the database, ordered by creation date in descending order.
    • Render a list of the fetched guestbook entries.
    • Include an HTML <form> that uses the addEntry Server Action. The form should have input fields for name and message.

Expected result

Your solution should consist of the completed code for the four files provided in the initial setup.

prisma/schema.prisma
The file should contain a valid GuestbookEntry model definition.

prisma
model GuestbookEntry {
  id        Int      @id @default(autoincrement())
  name      String
  message   String
  createdAt DateTime @default(now())
}

lib/prisma.ts
This file should correctly declare and export a global PrismaClient instance to ensure a single instance is used across the application.

typescript
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default prisma;

app/actions.ts
The file must start with the 'use server' directive. It should contain the addEntry function which correctly parses FormData, calls prisma.guestbookEntry.create, and then calls revalidatePath.

typescript
'use server';

import { revalidatePath } from 'next/cache';
import prisma from '@/lib/prisma';

export async function addEntry(formData: FormData) {
  const name = formData.get('name') as string;
  const message = formData.get('message') as string;

  await prisma.guestbookEntry.create({
    data: {
      name,
      message,
    },
  });

  revalidatePath('/');
}

app/page.tsx
This Server Component should correctly fetch data using prisma.guestbookEntry.findMany with the appropriate orderBy clause. The form should be linked to the server action with the action attribute. The fetched entries should be rendered on the page.

typescript
import { addEntry } from './actions';
import prisma from '@/lib/prisma';

export default async function GuestbookPage() {
  const entries = await prisma.guestbookEntry.findMany({
    orderBy: {
      createdAt: 'desc',
    },
  });

  return (
    <main>
      <h1>Guestbook</h1>
      
      <form action={addEntry}>
        <label htmlFor="name">Name:</label>
        <input type="text" id="name" name="name" required />
        
        <label htmlFor="message">Message:</label>
        <textarea id="message" name="message" required></textarea>
        
        <button type="submit">Sign</button>
      </form>
      
      <div>
        {entries.map((entry) => (
          <div key={entry.id}>
            <h3>{entry.name}</h3>
            <p>{entry.message}</p>
            <small>{entry.createdAt.toDateString()}</small>
          </div>
        ))}
      </div>
    </main>
  );
}
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.