Next.js Discord

Discord Forum

I have a function which calls the database directly in a server component page. Is it okay to do so?

Answered
Cuckoo wasp posted this in #help-forum
Open in Discord
Cuckoo waspOP
import { PostForm } from "@/components/Post/PostForm";
import { PrismaClient } from "@prisma/client";
import { Toaster } from "react-hot-toast";
import { cache } from 'react'
import { redirect } from 'next/navigation'

const prisma = new PrismaClient()

const getPostData =  cache( async (id) => {
        const postData = await prisma.post.findUnique({
            where: { id }
        })
        if (!postData) redirect('/dashboard/post/new')
        return postData
})

export default async function EditPost({params}) {
    const postId = params.id
    const postData = await getPostData(postId)
    return (
        <main className='flex flex-col justify-center m-5'>
            <h1>Edit Post</h1>
            <div className=''>
                <PostForm postData={postData}></PostForm>
            </div>
            <Toaster/>
        </main>
    )
}


I have this getPostData function in the server component page.jsx. It doesn't have any 'use server' directive in it to make it server action. Is it okay to do this?
Answered by Sloth bear
@Cuckoo wasp yeah you can call it like this since the code is executed on the server.

You only need to pay attention if you use the use client directive. If you do some data fetching there then it's problematic. But as long as you prefix all envs without NEXT_PUBLIC then it's also save that no env variables will be leaked.
View full answer

4 Replies

Sloth bear
@Cuckoo wasp yeah you can call it like this since the code is executed on the server.

You only need to pay attention if you use the use client directive. If you do some data fetching there then it's problematic. But as long as you prefix all envs without NEXT_PUBLIC then it's also save that no env variables will be leaked.
Answer
Sloth bear
Yeah ohly NEXT_PUBLIC env variables can be exposed on the client. If you have somehting like CONNECTION_STRING and you import it into a client component it will be undefined.
Cuckoo waspOP
Oh, didn't know that. Thanks for the info.