Next.js and Prisma: the dream team for modern web applications

Zwei Personen arbeiten gemeinsam an einem Computerbildschirm in einem modernen Büro.

Today I'll show you why Next.js and Prisma are the dream team for modern web projects - ideal if you're looking for a fast, flexible solution for developing and managing your application. Not in the mood for SQL fiddling? Then let's get started right away!

The most important facts in brief

  • Next.js offers fast, SEO-friendly websites and brings your projects to market quickly. 🏎️
  • Prisma is an ORM that saves you the SQL stress and makes database queries easy with TypeScript. 😌
  • With Prisma Accelerate, your database queries run super-fast - worldwide! 🌍
Zwei Männer formen mit ihren Händen ein Herz und trinken Bier.

What is Next.js

In short: Next.js is the turbo for your React application. Lightning fast, flexible and perfect for SEO. Whether you need server-side rendering (SSR) or static site generation (SSG) - Next.js has it covered.

Prisma explains 🤓

Prisma is an ORM (Object-Relational Mapping) that does the SQL work for you. With Code-First, you define your database tables directly in TypeScript, and Prisma automatically generates the appropriate SQL code - whether Postgres, MySQL or another database. Your CI/CD pipeline ensures that Prisma automatically performs migrations down to your production database so that your tables always match the code. 🚀

The best thing? Everything is typed, so it's always safe and error-free. So you can concentrate on developing your features without having to deal with complex database queries! 🎉

Prisma Accelerate 🌍💨

Prisma Accelerate is your turbo boost for database queries, especially if you use Next.js and Vercel. It combines global connection pools and caching directly in your existing database, which is perfect for serverless and edge environments like Vercel.

  • Connection pools in 15+ regions accelerate write operations and optimize your performance in serverless deployments.
  • Caching in 300+ global locations ensures that your queries are delivered at lightning speed - ideal for fast delivery of static and dynamic pages with Next.js.
  • Automatic scaling: Accelerate adapts dynamically to your traffic, no matter how high the load is.
  • Less load on the database: Reduce database accesses while increasing efficiency at the same time.

In combination with Next.js and Vercel, Prisma Accelerate ensures that your application is super performant - worldwide and without complicated infrastructure changes. Simply activate it, integrate it into the pipeline and off you go! 🚀

Ein Mann präsentiert vor einer kleinen Gruppe mit Laptop und Pflanzen im Hintergrund.

10 reasons why you should use Next.js and Prisma

1. faster time-to-market 🚀

With Next.js and Prisma, you can develop features efficiently and bring them live faster. Thanks to easy database access and flexible rendering, you save valuable time in the development process.

2. perfect integration with React Server Components ⚙️

Prisma can be seamlessly combined with React Server Components. This means you can handle server and database access directly in your components - without additional API overhead. Your application remains lean and performant.

Easy use of Prisma directly in React Server Components

'use server'

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

// Ensure you use a singleton to avoid too many open connections
const prisma = new PrismaClient();

export default async function UserList() {
  const users = await prisma.user.findMany();
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

3. server actions for client-side components 🔄

Prisma also works perfectly with Next.js Server Actions for client-side components. You no longer have to worry about APIs, but can work directly on the server and use the results immediately in the client.

Prism in Server Actions: Because APIs are overrated!

// src/app/actions.ts

'use server';

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

// Ensure you use a singleton to avoid too many open connections
const prisma = new PrismaClient();

export async function create(data: { name: string }) {
  return await prisma.user.create({ data });
}
// src/components/UserForm.tsx

'use client'

import React, { FC, FormEvent } from 'react';
import { create } from '@/app/actions';

export const UserForm: FC = () => {
  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault();
    const name = event.currentTarget.name.value;
    await create({ name });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" placeholder="Name" />
      <button type="submit">Benutzer erstellen</button>
    </form>
  );
};

4. no in-depth SQL know-how required 🧠

With Prisma, you don't need in-depth SQL knowledge. Prisma abstracts the database queries and generates the appropriate SQL code in the background. You can concentrate on development without having to deal with complex database knowledge.

Why make it complicated when it can be simple?

SELECT id, name, email
FROM users
WHERE email LIKE '%@example.com%'
ORDER BY created_at DESC;
const users = await prisma.user.findMany({
  where: {
    email: {
      contains: '@example.com',
    },
  },
  orderBy: {
    createdAt: 'desc',
  },
});

5. flat learning curve 🏞️

Prisma and Next.js have a flat learning curve - almost as flat as the Hüetliberg (for all those not from Zurich: the Hüetliberg is Zurich's "local mountain", which, according to our locals, does not deserve the name mountain). So you'll quickly become productive without a long training period.

6. automated database migrations 🔄

Migrations by hand? Not necessary! With Prisma, database migrations run automatically. You save time and can concentrate on creative solutions instead of writing manual scripts.

Bye-bye manual migrations: Prisma does it by itself!

// package.json

"scripts": {
    "dev": "npm run db:generate-client && npm run db:apply-migrations && next dev",
    "build": "npm run db:generate-client && next build",
    "vercel-build": "npm run db:generate-client && next build && npm run db:apply-migrations",
    "start": "npm run db:apply-migrations && next start",
    "lint": "next lint",
    "db:generate-client": "prisma generate",
    "db:generate-migration": "prisma migrate dev",
    "db:apply-migrations": "prisma migrate deploy"
  }

7. optimized performance and scalability 🌍

With Prisma Accelerate, your database queries are cached worldwide and delivered at lightning speed. Together with Next.js, you achieve top performance - no matter how many users are accessing your app at the same time.

8th database? Never mind! 💾

Whether MySQL, Postgres or MongoDB - Prisma supports a variety of databases. If you need to switch at any time, you can simply change the provider and the connection string and it will continue to run.

Switching from Postgres to MySQL? No problem!

datasource db {
  provider = "postgresql"
  url      = "postgresql://janedoe:mypassword@localhost:5432/mydb?schema=sample"
}
datasource db {
  provider = "mysql"
  url      = "mysql://janedoe:mypassword@localhost:3306/mydb"
}

9. better code quality and maintainability 🛠️

Thanks to type safety throughout the stack, you work with fewer errors and more stable code. Your productivity remains high and maintenance becomes child's play.

10. future-proof and community-supported 🔮

Both Next.js and Prisma have large, active communities and receive regular updates. Your project remains secure, stable and always at the cutting edge of technology.

Zwei Mitarbeiter lächeln und zeigen Peace-Zeichen und Daumen hoch.

Written by
Raphael Wirth

Next.js|September 2024

More Articles