Skip to content

Update Nuxt 4 prisma example to use server directory not shared #8385

@mikepage

Description

@mikepage

Example: https://github.com/prisma/prisma-examples/tree/latest/generator-prisma-client/nuxt4-starter-nodejs

Client-Side Exposure Risk: Generating the Prisma client in a shared directory accessible to both client and server means there's a risk of bundling database access code in the client bundle, even if accidentally.
Architecture Violation: In Nuxt 4, the clear separation is:

server/ - Server-only code (API routes, database access, business logic)
app/ or shared - Universal code that can run on both client and server

Security Concern: Database credentials and queries should never be accessible from client-side code. The Prisma Client should only exist in server-side code.

Update prisma schema.prisma, generate client in server directory.

# prisma/schema.prisma

generator client {
  provider   = "prisma-client"
  output     = "../server/generated/prisma"
  engineType = "client"
}

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

Update server/utils/prisma.ts, prisma.ts in utils with default export is auto-imported in api routes.

# server/utils/prisma.ts

import { PrismaClient } from '../generated/prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })

export default prisma

In server API routes the prisma client is globally available.

# server/api/posts/index.get.ts

export default defineEventHandler(async () => {
    const posts = await prisma.posts.findMany({  // ← prisma is automatically available
        // ...
    })
    return posts
})

Documentation: https://nuxt.com/docs/guide/directory-structure/server#server-utilities

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions