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
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
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.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
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 <@861471183890153492> 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.
Cuckoo waspOP
Thank you. Aas of your last paragraph talking about data fetching and env variables, are you saying this in context of Client Components? Also, I don't quite get the prefix NEXT_PUBLIC part.
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.