I have a NextJS application with a specific library that I want to ensure is only imported on the server side and not on the client side. To achieve this, I use import 'server-only'
. However, I also need to use this file for a local script. The issue arises when I run tsx scripts/test.ts
and encounter the server components error.
How can I make sure that a library is not imported on the client side?
This is my folder structure:
- app
- ...
- lib
- server-only-library.ts
- scripts
- local-script.ts
The contents of the files are as follows:
# server-only-library.ts
import 'server-only'
...
# local-script.ts
import Library from 'lib/server-only-library'
...
When testing, I received the following error:
$ tsx scripts/local-script.ts
/Users/michael/my-app/node_modules/server-only/index.js:1
throw new Error(
^
Error: This module cannot be imported from a Client Component module. It should only be used from a Server Component.
I attempted to address this using webpack by mapping it, but the error then only occurs during runtime on the client side and not during build time.
# next.config.js
const nextConfig = {
// doesn't work :( the import is mapped, but only throws in runtime
webpack: (config, { isServer, webpack }) => {
if (!isServer) {
config.resolve.alias = {
...config.resolve.alias,
'@secret/library': 'next/../server-only',
}
}
return config
},
}