Alejandro Zapien
Alejandro Zapien

Reputation: 123

How to resolve this typescript error on global node.js object

I am following this guide https://vercel.com/guides/nextjs-prisma-postgres to create a full stack app. Typescript is throwing an error in this snippet of code:

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

if (process.env.NODE_ENV === 'production') {
  prisma = new PrismaClient();
} else {
  if (!global.prisma) {
    global.prisma = new PrismaClient();
  }
  prisma = global.prisma;
}

export default prisma;

TypeScript is throwing a ts7017 on the global.prisma:

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.

Can someone help me understand this and how to fix? I set 'strict' to false in the tsconfig for the meantime and that supressed the issue for the meantime, though I'm sure having it off defeats the purpose of TS.

Upvotes: 8

Views: 7858

Answers (2)

Joël
Joël

Reputation: 1695

I could reproduce the same error with strict mode to true and @types/node package version 16

Update: see the other answer recommended from the docs here https://stackoverflow.com/a/69851359/1345244

This should work:

declare global {
  var prisma: PrismaClient; // This must be a `var` and not a `let / const`
}

import { PrismaClient } from "@prisma/client";
let prisma: PrismaClient;

if (process.env.NODE_ENV === "production") {
  prisma = new PrismaClient();
} else {
  if (!global.prisma) {
    global.prisma = new PrismaClient();
  }
  prisma = global.prisma;
}

export default prisma;

Upvotes: 20

SebasWebDev
SebasWebDev

Reputation: 51

According to the docs you need to declare the variable global first:

import { PrismaClient } from '@prisma/client'

declare global {
  var prisma: PrismaClient | undefined
}

export const prisma =
  global.prisma ||
  new PrismaClient({
    log: ['query'],
  });

if (process.env.NODE_ENV !== 'production') global.prisma = prisma;

You can also have a separate file globals.d.ts with the declaration in it.

Upvotes: 5

Related Questions