Usage with Amazon API Gateway

Amazon API Gateway adapter

The API Gateway adapter is supported for both Rest API(v1) and HTTP API(v2) use cases.

Example app

DescriptionURLLinks
API Gateway with NodeJS client.n/a

How to add tRPC

1. Install deps

  1. yarn add @trpc/server

2. Create a tRPC router

Implement your tRPC router. A sample router is given below:

server.ts

  1. import * as trpc from '@trpc/server';
  2. import { z } from 'zod';
  3. const appRouter = trpc.router().query('getUser', {
  4. input: z.string(),
  5. async resolve(req) {
  6. req.input; // string
  7. return { id: req.input, name: 'Bilbo' };
  8. },
  9. });
  10. // export type definition of API
  11. export type AppRouter = typeof appRouter;

3. Use the Amazon API Gateway adapter

tRPC includes an adapter for API Gateway out of the box. This adapter lets you run your routes through the API Gateway handler.

server.ts

  1. import { CreateLambdaContextOptions, lambdaRequestHandler } from '@trpc/server/adapters/lambda';
  2. const appRouter = /* ... */;
  3. // created for each request
  4. const createContext = ({
  5. event,
  6. context,
  7. }: CreateLambdaContextOptions) => ({}) // no context
  8. type Context = trpc.inferAsyncReturnType<typeof createContext>;
  9. export const handler = lambdaRequestHandler({
  10. router: appRouter,
  11. createContext,
  12. })

Build & deploy your code, now use your API Gateway URL to call your function.

EndpointHTTP URI
getUserGET https://<execution-api-link>/getUser?input=INPUT

where INPUT is a URI-encoded JSON string.

A word about payload format version

API Gateway has two different event data formats when it invokes a Lambda. For REST APIs they should be version “1.0”(APIGatewayProxyEvent), but you can chose which for HTTP APIs by stating either version “1.0” or “2.0”.

  • Version 1.0: APIGatewayProxyEvent
  • Version 2.0: APIGatewayProxyEventV2

To infer what version you might have, supply the context as following:

  1. function createContext({
  2. event,
  3. context,
  4. }: CreateLambdaContextOptions<APIGatewayProxyEvent>) {
  5. ...
  6. }
  7. // CreateLambdaContextOptions<APIGatewayProxyEvent> or CreateLambdaContextOptions<APIGatewayProxyEventV2>

Read more here about payload format version