How to use filesystem / node-only packages in server components? #50244
-
|
If a component isn't marked with For example, I want an image component that uses a dependency that relies on the filesystem to generate placeholders: import fs from "node:fs/promises";
import path from "node:path";
import Image, { ImageProps } from "next/image";
import { getPlaiceholder } from "plaiceholder";
export default async function ImageWithPlaceholder({
src,
...rest
}: ImageProps) {
const file = await fs.readFile(path.join("./public", src));
const { base64 } = await getPlaiceholder(file);
return (
<Image src={src} placeholder="blur" blurDataURL={base64} {...rest}></Image>
);
}However, this doesn't work, because "fs" is undefined. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
|
Hi, You can do something called, poisoning to prevent accidental imports: https://nextjs.org/docs/getting-started/react-essentials#the-server-only-package Also
I think the problem you have is that a What you can do is use composition, at some layout/page level, using this pattern: https://nextjs.org/docs/getting-started/react-essentials#recommended-pattern-passing-server-components-to-client-components-as-props that way React creates a "slot" where the server component results are placed. |
Beta Was this translation helpful? Give feedback.
Hi,
You can do something called, poisoning to prevent accidental imports: https://nextjs.org/docs/getting-started/react-essentials#the-server-only-package
Also
use clientmeans that the JS that drives the component is sent to the client for hydration. There's aclient-onlypoison you can use.I think the problem you have is that a
use clientcomponent is directly importing yourImageWithPlaceholder- when ause clientcomponent enters the React tree, all of its direct children are client components. Otherwise, everything is a Server Component by default.What you can do is use composition, at some layout/page level, using this pattern: https:…