Skip to content

[Next13 App dir] Bug with server-only being used in an API route handler #43700

@KolbySisk

Description

@KolbySisk

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 22.0.0: Mon Aug  1 06:32:20 PDT 2022; root:xnu-8792.0.207.0.6~26/RELEASE_ARM64_T6000
Binaries:
  Node: 16.15.0
  npm: 8.5.5
  Yarn: N/A
  pnpm: N/A
Relevant packages:
  next: 13.0.6
  eslint-config-next: 13.0.6
  react: 18.2.0
  react-dom: 18.2.0

Which area(s) of Next.js are affected? (leave empty if unsure)

App directory (appDir: true)

Link to reproduction - Issues with a link to complete (but minimal) reproduction code will be addressed faster

https://github.com/KolbySisk/next-server-only-bug

To Reproduce

  1. Create a client component that makes a request to an api route (A form that posts data to an api route, for example)
    2.npm i server-only
  2. Add import "server-only"; to the api route.
  3. Run and make the request to the api route.

See error:

You're importing a component that needs server-only. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.

Describe the Bug

API routes are handled only on the server, so I would expect import "server-only"; to work fine.

More realistically, I have a function which includes sensitive information that I want to ensure only runs on the server. It can be used in both a server component, and an API route, given the context.

I'm also curious how Next even knows about the relationship between a client component and an API route handler.

Expected Behavior

Code is executed as expected without the error.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

NEXT-1385

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIssue was opened via the bug report template.linear: nextConfirmed issue that is tracked by the Next.js team.locked

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions