Prisma and Nextjs

Ali Khan
Tensor Labs
Published in
4 min readAug 8, 2023
Next.js and Prisma

Elevate Your Next.js Projects with Prisma. Seamlessly Integrate Database Management for Enhanced Web Development. If you’re ready to take your Next.js projects to the next level, you’re in the right place. In this article, we will look into the powerful world of Prisma, the open-source next-generation ORM.

Prisma and Next.js form an exceptional partnership, seamlessly enhancing the realm of database management and interaction within web applications. But before we embark on our exploration of the dynamic synergy between Next.js and Prisma, let’s delve into the realm of Prisma itself — its essence, significance, and the compelling reasons that underscore its indispensability.

Prisma: Prisma stands as an open-source, cutting-edge ORM (Object-Relational Mapping) that facilitates the efficient management and interaction with databases. It comprises three essential components:

  • Prisma Client: This auto-generated, type-safe query builder supports Node.js and TypeScript, enabling simplified and secure database queries.
  • Prisma Migrate: A schema migration tool, Prisma Migrate empowers you to seamlessly evolve your database schema from the initial prototype to a production-ready state.
  • Prisma Studio: While the majority of Prisma is open-source, Prisma Studio, a graphical user interface, enables you to visualize and modify database information locally.
Prisma Components

Prisma Studio is the only part of Prisma that is not open source and you can only run Prisma studio locally.

Prisma currently supports PostgreSQL, MySQL, SQLie and Microsoft SQL Server and work inside any JavaScript or TypeScript Enviroment.

Next.js and Prisma Integration:

Next.js seamlessly integrates with Prisma, offering diverse methods to access your database:

Next.js blurs the lines between client and serve. It supports pre-endering pages at build time (SSG) or request time (SSR).

Prisma is the best companion if your need to work with database in a Next.js app.

It is up to you whether you want to access you db with prisma static site or at request time meaning during server side rendering or use Next.js API Routes or using a complete standalone server. Its totally up to you.

Next.js and Prisma Integration

Static Site Generation (SSG) with Prisma:

In Next.js, the getStaticProps function, executed at build time, supports static site generation. Prisma can be utilized within this function to send queries to your database, effectively fetching data for static pages like blogs or marketing sites.

export async function getStaticProps() {

const prisma = new PrismaClient()

const posts = await prisma.post.findMany()

return {

props: { posts }

}

Server-Side Rendering (SSR) with Prisma:

For server-side rendering at request time, the getServerSideProps function in Next.js comes into play. This function incorporates Prisma to send queries to your database, ensuring dynamic data retrieval when user authentication or real-time updates are needed.

// Fetch posts from authenticated user

// (in /pages/index.tsx)

export const getServerSideProps = async ({ req }) => {

const token = req.headers.AUTHORIZATION

const userId = await getUserId(token)

const posts = await prisma.post.findMany({

where: {

author: { id: userId },

},

})

return { props: { posts } }

}

Server-Side Rendering (SSR)

Next.js API Routes and Standalone Servers with Prisma:

Prisma can be harnessed within Next.js API routes or standalone server setups to execute database queries through REST or GraphQL. This offers flexibility in data retrieval methods, empowering you to customize your API architecture.

// Fetch all posts (in /pages/api/posts.ts)

const prisma = new PrismaClient()

export default async function handle(req, res) {

const posts = await prisma.post.findMany()

res.json(posts)

}

Using Prisma with a standalone server

Next.js can also request data from a standalone web server. The server can be implemented with any HTTP or GraphQL library, such as Express, Koa, Fastify or Apollo Server — or anything else that can expose an API to your Next.js frontend. Here is an example for a REST API with a sample /api/posts route written with Express:

// Fetch all posts in an Express route

app.get(‘/posts’, async (req, res) => {

const prisma = new PrismaClient()

const posts = await prisma.post.findMany()

res.json(posts)

})

It’s important to note that while using Prisma in Next.js API routes or standalone servers, employing the Prisma data proxy or an external connection pooler is recommended for optimal performance and to prevent exceeding the database connection limit.

Upon fetching the data, you can exhibit it on your Next.js page. An example showcases how to employ the Vercel SWR library to fetch and display posts fetched from the API.

// Display posts in frontend (in /pages/index.tsx)

export default function App() {

const { data, error } = useSWR(‘/api/posts’, fetcher)

if (error) return <div>An error occured.</div>

if (!data) return <div>Loading …</div>

return (

<ul>

{data.posts.map(post => (

<li key={post.id}>{post.title}</li>

))}

</ul>

)

}

When using GraphQL, you can use any GraphQL client like urql or Apollo Client in your Next.js page instead.

GraphQL

Incorporating Prisma into your Next.js application enriches database management and querying, ultimately enhancing the functionality and user experience of your web application.

--

--