Querying a database directly

Intermediate · 7 min

Call an ORM or database client from a Server Component, keep the data layer server-only, deduplicate with React.cache, and handle synchronous drivers.

Before thisFetching data in Server ComponentsEnvironment variables and server-only code

Codevolution · 7 min

Querying a database directly

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A Server Component can call an ORM or database client directly, because that code and its credentials never reach the browser bundle.
  • Skipping an API layer removes a network hop and a whole class of glue code, but authorization is still your job inside every query path.
  • Keep queries in a small data-access module marked server-only so a Client Component cannot import it by accident.
  • Wrap non-fetch data functions in React.cache to deduplicate repeated calls within one request, since only fetch is memoized automatically.
  • A synchronous driver such as better-sqlite3 finishes during prerendering, so call connection() before the query when each request needs fresh rows.

Why skip the API

The classic web-app shape has three layers: a browser, an API server, and a database. The browser asks the API for JSON, the API asks the database, and every feature needs both an endpoint and a client that calls it.

Server Components already run on a server. A component that needs posts can ask the database itself, which makes the middle layer optional for data that only your own UI reads. The official docs put it plainly: because rendering happens on the server, credentials and query logic are not included in the client bundle, so you can query with an ORM or database client directly.

// app/blog/page.tsx
import { db, posts } from '@/lib/db'

export default async function Page() {
  const allPosts = await db.select().from(posts)
  return (
    <ul>
      {allPosts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

That is the whole feature. No route handler, no fetch, no serialization step for you to write.

Keep the data layer where it belongs

The thing to protect against is a query function ending up in a client bundle. Put your queries in one module, and mark it so that importing it from a Client Component is a build error. The server-only package does this; see environment variables and server-only code.

// lib/data.ts
import 'server-only'
import { cache } from 'react'
import { db, posts, eq } from '@/lib/db'

export const getPost = cache(async (id: number) => {
  return db.query.posts.findFirst({ where: eq(posts.id, id) })
})

A data-access module like this is also the right place for the authorization check. A direct query skips the API server, and that server is where many apps used to enforce permissions. The check has to move with the query. If getPost returns rows for any id to anyone who asks, hiding the link in the UI protects nothing.

Why React.cache shows up here

Automatic memoization applies to fetch. A function that calls Prisma or Drizzle is not fetch, so calling it from a page and again from generateMetadata runs the query twice. Wrapping it in React.cache fixes that: calls with the same arguments in one request share one result. The cache is scoped to the request, with no sharing between requests, which is what you want for per-user data. The next lesson goes deeper.

Cache Components and database queries

Under Cache Components, a database call is uncached data, the same as an uncached fetch. Either wrap the component in <Suspense> so it streams, or cache the function with use cache and a cacheLife. Otherwise next build stops with the blocking-route error from the previous lesson.

One case surprises people. A synchronous driver such as better-sqlite3 or Node’s built-in node:sqlite completes during prerendering, so its result would be frozen into the static shell. The docs’ fix is to call connection() before the query when you need per-request data:

import { connection } from 'next/server'

export async function getVisitorCount() {
  await connection() // prerendering stops here
  return db.prepare('SELECT value FROM counters WHERE name = ?').get('visitors')
}

Connections in serverless hosting

A long-running Node server opens a pool of database connections and reuses them. On serverless platforms each invocation can start a fresh process, and many of them at once can exhaust a database’s connection limit. Check your database’s guidance on connection pooling or a serverless-friendly driver before you deploy; it is a deployment concern more than a Next.js one.

What the video covers

Codevolution’s tutorial sets up Prisma with SQLite, defines models, runs migrations, writes CRUD operations, and then fetches rows inside a Next.js page. The chapters are: why direct database access in server components, SQLite and Prisma, setup, models and migrations, CRUD with Prisma, and fetching data in a page. It is a Next.js 15 recording and uses SQLite, so it does not discuss pooling or Cache Components.

Where this fits

Now that you can get data from an API or a database, the next question is how often you ask. Next: request memoization and parallel fetching.

Check yourself

  1. 01Why is it safe to put a database query inside a Server Component?

    Server Components render on the server and only their output is sent to the browser, so the query, the connection string, and the ORM never enter a client bundle.

  2. 02Why can two components calling the same Prisma or Drizzle function still hit the database twice in one request?

    Automatic memoization only covers fetch GET requests, so a plain database function runs each time it is called unless you wrap it in React.cache.

  3. 03Why is a query in a Server Component still not a substitute for authorization?

    The page or action can be reached by someone who should not see the row, so each data function must check who is asking before it returns data.

  4. 04When would you call connection() before a database query?

    When the driver is synchronous and the data must be fresh per request, because a synchronous query completes during prerendering and would otherwise be baked into the static shell.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark