A clever abstraction attempt!
Unfortunately, you've hit a fundamental limitation of Next.js' architecture. The error message is telling you that next/headers (which provides the headers() function) is only available in Server Components, which are a new paradigm introduced in the App Router.
In the Pages Router, you're still using Page Components, which don't support Server Components' features like next/headers. When you try to import headers() in a Page Component, Next.js complains because it can't execute that code in the Pages Router context.
Your abstraction, although elegant, can't bridge this gap because headers() is not compatible with the Pages Router.
Here are a few alternatives to help you ease the migration:
1. Conditional imports
Split your setHeader function into two separate implementations, each importing the required module only when needed:
// setHeader.pages.ts (for Pages Router)
import type { OutgoingMessage } from 'http';
export const setHeader = (name: string, value: string, response: OutgoingMessage) => {
response.setHeader(name, value);
};
// setHeader.app.ts (for App Router)
import { headers } from 'next/headers';
export const setHeader = async (name: string, value: string) => {
const header = await headers();
header.set(name, value);
};
Then, in your shared code, conditionally import the correct setHeader function based on the environment:
// utils.ts
import { useRouter } from 'next/router'; // or next/navigation for App Router
const isAppRouter = () => {
try {
// next/navigation is only available in App Router
require('next/navigation');
return true;
} catch {
return false;
}
};
const setHeader = isAppRouter()
? require('./setHeader.app').setHeader
: require('./setHeader.pages').setHeader;
export { setHeader };
2. Wrap headers() in a compatibility layer
Create a wrapper function that only imports headers() when executed in an App Router context. This uses a dynamic import() to lazy-load headers():
// headersCompat.ts
let headersImpl: typeof import('next/headers')['headers'] | undefined;
export const headersCompat = async () => {
if (!headersImpl) {
try {
const { headers } = await import('next/headers');
headersImpl = headers;
} catch {
// Swallow the error; we're in Pages Router context
return undefined;
}
}
return headersImpl ? headersImpl() : undefined;
};
Update your original setHeader function to use this compatibility layer:
// setHeader.ts
import { headersCompat } from './headersCompat';
import type { OutgoingMessage } from 'http';
export const setHeader = async (
name: string,
value: string,
response?: OutgoingMessage,
) => {
if (response) response.setHeader(name, value);
const header = await headersCompat();
if (header) header.set(name, value); // Only set if we're in App Router
};
In this approach, headers() is only imported and executed when running in an App Router environment. If headersCompat() returns undefined (i.e., Pages Router), the header.set() line is simply skipped.
3. Fork your code (the most straightforward approach)
Accept that some code will be duplicated and maintain two separate setHeader functions:
- In your Pages Router code, keep using
response.setHeader() directly.
- In your App Router code, use the
headers() function.
As you migrate more pages to the App Router, you can gradually phase out the Pages Router-specific implementation.
Choose the solution that best balances your needs:
- Conditional imports (Option 1) are clean but require more setup.
- The compatibility layer (Option 2) keeps your shared code intact but adds a dynamic import overhead.
- Forking your code (Option 3) is the most straightforward but leads to some duplication.
Good luck with your migration!