server-only is a small package that marks a module as server code. If client code imports it, the build fails.
You import it at the top of a module with import "server-only". If a Client Component imports that module, directly or through a chain of imports, the build fails with a clear error.
This protects modules that use secrets, such as API keys or database clients, from being bundled into the browser by mistake. Without it, an env var without the NEXT_PUBLIC_ prefix would just be undefined on the client. That hides the mistake instead of stopping it.
There is a matching client-only package for modules that must only run in the browser, such as code that uses window.
import "server-only"marks a module as server-only.- Importing that module from client code fails the build.
- It protects secrets and database access.
client-onlyis the browser counterpart.