How to load server-side libs (like fs
or os
) in collections only in case when code runs on the server?
#2111
-
Hello everyone. What I want to do? I have beforeOperation: [
async ({ args, operation }) => {
const { req, data } = args;
if (operation === "create") {
try {
// Here I tried to cheat and load lib via dynamic imports. It doesn't work.
// Also I tried ESM imports and require(). The same story.
const { downloadFile } = await import("../src/utils/downloadFile");
const { default: os } = await import("os");
const filePath = `${os.tmpdir()}/randomfile`;
if (data.picture) {
await downloadFile(data.picture, filePath);
const avatar = await req.payload.create({
collection: "avatars",
filePath,
});
return {
...args,
data: {
...data,
avatar: avatar.id,
},
};
}
} catch (error) {
console.log({ error });
}
return args;
}
},
],
}, Where is the problem? When I add this code to collection Error as text:
I'm new with Pyload CMS, so I do not understand properly how it works. But I have assumption that Payload code shares between server-side and client-side, so if I add server-specific lib to collections it cause a problem on client-side. Question: How to load server-side libs (like Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
@jmas you're exactly right, you just need to alias your server-only code. Here are the docs that describe this in detail: https://payloadcms.com/docs/admin/webpack#aliasing-server-only-modules and here's a real-world example of this: https://github.com/payloadcms/template-ecommerce/blob/main/src/payload.config.ts#L35. Would this work for you? |
Beta Was this translation helpful? Give feedback.
@jmas you're exactly right, you just need to alias your server-only code. Here are the docs that describe this in detail: https://payloadcms.com/docs/admin/webpack#aliasing-server-only-modules and here's a real-world example of this: https://github.com/payloadcms/template-ecommerce/blob/main/src/payload.config.ts#L35. Would this work for you?