new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

Next.js · Guides · all subjects

security best practices

5 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Preventing environment poisoning with server-only code

JavaScript modules can be shared between both Server and Client Components modules, making it possible to accidentally import server-only code (like code using API_KEY environment variables) into the client. Use the server-only package to prevent this.

Using server-only package to prevent accidental client imports

Use the 'server-only' npm package to prevent accidental usage of server-only code in Client Components. Import 'server-only' at the top of files containing server-only code. This causes a build-time error if the module is imported into a Client Component.

Using client-only package for client-only logic

Use the 'client-only' npm package to mark modules that contain client-only logic, such as code that accesses the window object. This prevents accidental usage in Server Components.

Environment variables and client bundle exposure

Only environment variables prefixed with NEXT_PUBLIC_ are included in the client bundle. If variables are not prefixed, Next.js replaces them with an empty string. This prevents API keys and other secrets from being exposed to the client.

Next.js handles server-only and client-only imports internally

Next.js handles server-only and client-only imports internally to provide clearer error messages when a module is used in the wrong environment. The contents of the server-only and client-only packages from NPM are not used by Next.js. Next.js provides its own type declarations for these packages for TypeScript configurations where noUncheckedSideEffectImports is active.

Give your agent this brain