philos
philos

Reputation: 86

How to use PrismaClient and usePathname together in the same component with Next.js 13's App Router

I'm trying to create a Header component that gets navigation links from a database and shows which one is active currently.

I use Next.js 13 (app router) and Prisma as ORM. To get the current pathname I have to include 'use client' otherwise, I cannot get the pathname because "usePathname only works in Client Components." But when I include 'use client' I cannot use PrismaClient because I get an error that says "PrismaClient is unable to be run in the browser." How can I use these two together?

Here's the code I used for Header.tsx component:

'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export async function getCategories() {
  const categories = await prisma.categories.findMany()
  return categories
}

export default async function Header(){
  const pathname = usePathname()
  const categories = await getCategories()
  return(
    <header>
      {categories.map((category) => (
        <Link href={"/"+category.slug} className={pathname == "/"+category.slug ? "menu-item item-active" : "menu-item"}>
           <span>{category.name}</span>
        </Link>
      ))}
    </header>
  )
}

Upvotes: 0

Views: 652

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 45883

You cannot have both use client and PrismaClient in the same component. You could create a client Nav component and pass the categories as prop:

import Link from 'next/link'
import { PrismaClient } from '@prisma/client'
import Nav from "./Nav"

const prisma = new PrismaClient()

export async function getCategories() {
  const categories = await prisma.categories.findMany()
  return categories
}

export default async function Header(){
  const categories = await getCategories()
  return(
    <header>
     <Nav categories={categories} />
    </header>
  )
}
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'

export default async function Nav({categories}){
  const pathname = usePathname()
 
  return(
    <>
      {categories.map((category) => (
        <Link href={"/"+category.slug} className={pathname == "/"+category.slug ? "menu-item item-active" : "menu-item"}>
           <span>{category.name}</span>
        </Link>
      ))}
    </>
  )
}

Upvotes: 2

Related Questions