Note: API routes are still only supported in the pages
folder, not app
.
I was playing around with using API routes with the experimental app dir stuff in Next 13, and I was frustrated at having to use completely different code paths for accessing the request headers and cookies compared to in server components. So I hacked together a workaround which you definitely shouldn't use.
Usage requires two steps, one is easy, the other is invasive:
- Wrap any API routes with the withRequestContext function defined in this gist
- Make sure any use of
headers()
andcookies()
in the code paths of these API routes only uses local imports for these functions. Module-level imports will erroneously trigger some logic in Next whereby it thinks a client component is being rendered, and throws an exception which I haven't been able to suppress without something likepatch-package
:
So instead of:
import { cookies, headers } from "next/headers";
export function myDataLoadingThing() {
// do something with cookies() or headers()
}
Do:
export async function myDataLoadingThing() {
const { cookies, headers } = await import("next/headers");
// do something with cookies() or headers()
}