server-only in proxy
Answered
Paul posted this in #help-forum
PaulOP
Can I use
import 'server-only' in a function called in the proxy.ts in next.js?3 Replies
you can definitely use import 'server-only' in your proxy.ts file, provided that this proxy file is exclusively executed and imported on the server side (such as inside Route Handlers, Server Actions, or Server Components).
Keep in mind that server-only is a build-time guard. If proxy.ts is ever imported into a Client Component (modules marked with 'use client'), the build will fail immediately.
If your proxy.ts handles sensitive server-side operations (like API keys, internal microservice routing, or database fetching), adding import 'server-only' at the very top of the file is actually a best practice to ensure those secrets never accidentally leak to the client bundle.
Keep in mind that server-only is a build-time guard. If proxy.ts is ever imported into a Client Component (modules marked with 'use client'), the build will fail immediately.
If your proxy.ts handles sensitive server-side operations (like API keys, internal microservice routing, or database fetching), adding import 'server-only' at the very top of the file is actually a best practice to ensure those secrets never accidentally leak to the client bundle.
PaulOP
Hmm, I think you miss understand what I mean by proxy file: https://nextjs.org/docs/app/api-reference/file-conventions/proxy this will never be imported anywhere.
My question is around importing a function that has
My question is around importing a function that has
server-only into the next.js proxy, eg:// some-server-only-check.ts
import "server-only"
export function someServerOnlyCheck(){
//...
}
// proxy.ts
import { someServerOnlyCheck } from "./some-server-only-check"
export function proxy(request: NextRequest) {
if(someServerOnlyCheck){
// do something
}
return NextResponse.next()
}