#Check if inside of Client or Server component
1 messages · Page 1 of 1 (latest)
Based on the information provided in the extracts, there isn't a direct way to check if you're inside a server component. However, you can manage your code in a way that ensures server-only code doesn't leak into the client environment.
One way to do this is by using the server-only package. This package gives a build-time error if a developer accidentally imports a module that contains server-only code into a Client Component. Here's how you can use it:
- Install the package:
npm install server-only
- Import the package into any module that contains server-only code:
import 'server-only'
export async function getData() {
const res = await fetch('<https://external-service.com/data',> {
headers: {
authorization: process.env.API_KEY,
},
})
return res.json()
}
Now, any Client Component that imports getData() will receive a build-time error explaining that this module can only be used on the server. This way, you can ensure that server-only code doesn't leak into the client environment.
For more details, refer to the Next.js documentation on Server and Client Composition Patterns (https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns).