Skip to main content

Next.js Edge Runtime & App Router

The Next handler can be used for the Pages Router Edge Runtime or for the App Router.

The handler file needs to be a catch-all route file, which is a file that matches the pattern [...ts-rest].ts pattern. In the case of the Pages Router, it must be named exactly [...ts-rest].ts.

import { createNextHandler } from '@ts-rest/serverless/next';
import { contract } from './contract';
import { router } from './router';

export const handler = createNextHandler(
contract,
router,
{
handlerType: 'app-router',
// handlerType: 'pages-router-edge',

// rest of options
}
);

Example Usage

Context Object

In addition to the regular context properties, the context object for Next handlers includes the following additional properties:

  • nextRequest: NextRequest: The Next.js specific request object.
import { createLambdaHandler } from '@ts-rest/serverless/aws';
import { contract } from './contract';

export const handler = createLambdaHandler(
contract,
{
getPost: async ({ params: { id } }, { nextRequest, responseHeaders }) => {
responseHeaders.set('x-geo-country', nextRequest.geo.country);

return {
status: 200,
body: {
id,
title: 'Hello, World!',
},
};
},
}
);