DEV Community

MILIND D JAIN
MILIND D JAIN

Posted on

Database connection in NextJS (App Router)

In today's post, we will be learning about the good way of connecting the NextJS application to the database via PrismaORM.

For those who are new to Prisma ORM, here is the quick gist of it. Prisma ORM ( Object Relational Mapping) is the tool that makes communication with the database easy. So, let's say you want to connect to any database, be it MySQL, PostgreSQL, SQLite, or MongoDB, then the straightway is to write a query that is understood by the database we are using.

Now, this way is not wrong, but it gives rise to many problems like -

  1. The developer needs to know the proper syntax for the query 😟.
  2. A small mistake can take hours to debug.
  3. More vulnerable to errors, which in turn makes switching to a different database difficult.

ORM / ODM are saviours here, they work as the middle translator between the database and our application. So, no need to worry about the actual syntax of the database we want to use.

Now, let's talk about a good way of connecting the Prisma client for database connection in the NextJS app router. Here is the code, followed by the explanation in brief detail.

import { PrismaClient } from "@/generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined;
};

const connectionString = `${process.env.DATABASE_URL}`;

const adapter = new PrismaPg({connectionString});

export const prisma = globalForPrisma.prisma || new PrismaClient({adapter});


if(process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

Enter fullscreen mode Exit fullscreen mode

Creating a prisma client and connecting to the database can be done in 2 to 3 lines, but why so much of surrounded code? Here is the reason -

Let's say when we deploy our NextJS application, then it is not like we have only one instance, but it is loaded to multiple instances. Means multiple instances are already sitting to handle traffic, but that does not mean we have that many db connections.

Whenever a user hits the application from the browser, that request creates a new db connection on the instance it hits. Now, if another request comes to that same instance, then via module caching creation of a new Prisma client is prevented.

But in the case of a non-prod environment, like development, we have hot-reloading, hence to prevent db connection on each hot reload, we use a global store to cache it.

Top comments (0)