Conversation
|
IMO, this is all knowledge not specific to aws-lambda-fastify, but general to how AWS Lambda works in combination with NestJS... |
|
I would say it's about how aws-lambda-fastify works in combination with NestJS, not just generic AWS Lambda. But, I do see your point; however, there is an open issue inquiring about this which led to some more discussion and someone asked me to update the readme in order to persist the knowledge. Maybe that's not the right place for it, though. |
|
I think a better place for this documentation is on the Nest.js website. |
That's exactly what I meant 😉 |
|
@mcollina I agree. I'll see about getting this added to their documentation. |
|
@Uzlopak ok for you if we close this PR in favor to document it on the Nest.js side somewhere? |
|
I am totally ok with it as long it is somewhere documented?! Is it likely that nest js will accept that additional documentation? |
|
Just want to say that I was looking around today and was very happy to find a PR here with documentation about using Next.js with Fastify on Lambda. Is there a PR for Nest.js documentation I can upvote or whatever? I really appreciate being able to find some documentation somewhere on this so I hope it gets out there on the web somewhere somehow... |
|
@Jwagner347 I see some issues with the code in the README. Mostly variable names and types not lining up because the code is combined. Here's how it should look: import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import awsLambdaFastify, { PromiseHandler } from '@fastify/aws-lambda';
import fastify, { FastifyInstance, FastifyServerOptions } from 'fastify';
import { Context, APIGatewayProxyEvent } from 'aws-lambda';
import { Logger } from '@nestjs/common';
interface NestApp {
app: NestFastifyApplication;
instance: FastifyInstance;
}
let cachedNestApp;
async function bootstrap(): Promise<NestApp> {
const serverOptions: FastifyServerOptions = {
logger: (process.env.LOGGER || '0') == '1',
};
const instance: FastifyInstance = fastify(serverOptions);
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(instance),
{
logger: !process.env.AWS_EXECUTION_ENV ? new Logger() : console,
},
);
const CORS_OPTIONS = {
origin: '*',
allowedHeaders: '*',
exposedHeaders: '*',
credentials: false,
methods: ['GET', 'PUT', 'OPTIONS', 'POST', 'DELETE'],
};
app.register(require('fastify-cors'), CORS_OPTIONS);
app.setGlobalPrefix(process.env.API_PREFIX);
await app.init();
return {
app,
instance,
};
}
export const handler = async (
event: APIGatewayProxyEvent,
context: Context,
): Promise<PromiseHandler> => {
if (!cachedNestApp) {
const nestApp: NestApp = await bootstrap();
cachedNestApp = awsLambdaFastify(nestApp.instance, {
decorateRequest: true,
});
}
return cachedNestApp(event, context);
};However, we have a bigger issue and that is a type mismatch when adapting Fastify: I'll see if I can figure it out and update below. |
|
I submitted an bug report issue here. |
|
OK I took another crack at fixing it using the Fastify instance from the |
|
I got it working! The code that works is as follows: I had to make sure that the Fastify version was the same between what was installed here and what |
There was a problem hiding this comment.
Pull request overview
This PR adds documentation for using @fastify/aws-lambda with NestJS, addressing issue #115 which requested examples of integrating the library with NestJS. The documentation includes two sections: basic NestJS setup and NestJS with GraphQL integration.
Changes:
- Added a "Usage with NestJS" section with a complete example showing how to integrate NestJS with aws-lambda-fastify
- Added a "Usage with NestJS/GraphQL" section explaining how to handle GraphQL schema files in a Lambda environment
- Included explanation of lambda caching patterns to minimize cold-start times
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| ], | ||
| controllers: [AppController], | ||
| providers: [AppService], | ||
| }) |
There was a problem hiding this comment.
The code example is incomplete and missing the class decorator and export. The example should start with export class AppModule {} to be a complete and valid TypeScript class definition.
| }) | |
| }) | |
| export class AppModule {} |
| You will also need to modify your `app.module.ts` file: | ||
|
|
||
| ### app.module.ts | ||
| ```typescript |
There was a problem hiding this comment.
The app.module.ts example is missing necessary import statements. At minimum, it should include imports for Module, GraphQLModule, MercuriusDriverConfig, GqlModuleOptions, MercuriusDriver, join, and any other referenced symbols like createXYZLoader, XYZService, XYZModule, AppController, and AppService. Without these imports, the code example cannot be used as-is.
| ```typescript | |
| ```typescript | |
| import { Module } from '@nestjs/common'; | |
| import { GraphQLModule, GqlModuleOptions } from '@nestjs/graphql'; | |
| import { MercuriusDriver, MercuriusDriverConfig } from '@nestjs/mercurius'; | |
| import { join } from 'path'; | |
| import { createXYZLoader } from './xyz.loader'; | |
| import { XYZService } from './xyz.service'; | |
| import { XYZModule } from './xyz.module'; | |
| import { AppController } from './app.controller'; | |
| import { AppService } from './app.service'; |
| let cachedNestApp; | ||
|
|
||
| async function bootstrapServer(): Promise { |
There was a problem hiding this comment.
The variable cachedNestApp is missing a type annotation. It should be typed to match what awsLambdaFastify returns. Consider adding a type annotation such as let cachedNestApp: PromiseHandler | undefined; or let cachedNestApp: any; for clarity.
| let cachedNestApp; | |
| async function bootstrapServer(): Promise { | |
| let cachedNestApp: PromiseHandler | undefined; | |
| async function bootstrapServer(): Promise<NestApp> { |
| context: Context, | ||
| ): Promise<PromiseHandler> => { | ||
| if (!cachedNestApp) { | ||
| const nestApp = await bootstrap(); |
There was a problem hiding this comment.
The function being called is bootstrap() but the function defined above is named bootstrapServer(). This is a critical bug that would prevent the code from working. The call should be changed to bootstrapServer().
| const nestApp = await bootstrap(); | |
| const nestApp = await bootstrapServer(); |
| methods: ['GET', 'PUT', 'OPTIONS', 'POST', 'DELETE'], | ||
| }; | ||
|
|
||
| app.register(require('fastify-cors'), CORS_OPTIONS); |
There was a problem hiding this comment.
The package fastify-cors has been deprecated and replaced with @fastify/cors. The code should use the newer package instead. Update the line to use @fastify/cors and consider importing it at the top of the file rather than using require() inline, which would be more consistent with the TypeScript imports used elsewhere in the example.
| async function bootstrapServer(): Promise { | ||
|
|
||
| const serverOptions: FastifyServerOptions = { | ||
| logger: (process.env.LOGGER || '0') == '1', |
There was a problem hiding this comment.
Using == for comparison is not recommended in TypeScript/JavaScript. Use strict equality === instead: (process.env.LOGGER || '0') === '1'.
| logger: (process.env.LOGGER || '0') == '1', | |
| logger: (process.env.LOGGER || '0') === '1', |
| export const handler = async ( | ||
| event: APIGatewayProxyEvent, | ||
| context: Context, | ||
| ): Promise<PromiseHandler> => { |
There was a problem hiding this comment.
The return type Promise<PromiseHandler> appears to be incorrect. The PromiseHandler type from @fastify/aws-lambda represents the handler function type, not the return value of the handler. The handler should return the actual response from the lambda proxy, which is typically something like Promise<APIGatewayProxyResult>. Consider removing the explicit return type or using the correct return type.
| ): Promise<PromiseHandler> => { | |
| ) => { |
|
|
||
| let cachedNestApp; | ||
|
|
||
| async function bootstrapServer(): Promise { |
There was a problem hiding this comment.
The function bootstrapServer is missing the generic type parameter for its Promise return type. The return type should be Promise<NestApp> instead of just Promise.
| async function bootstrapServer(): Promise { | |
| async function bootstrapServer(): Promise<NestApp> { |
| Notice we are caching the initialized app. In a lambda environment, the handler will be called on each new request. Anything outside the handler may be cached between calls, which lasts as long as AWS has kept the same lambda execution environment up for your function. By storing the initialized app as a variable, we can minimize the cold-start time of our app since it will be constructed once per execution environment spin up. | ||
|
|
||
| ## Usage with NestJS/GraphQL | ||
| In addition to the above, when using NestJS with GraphQL in a lambda environment, you will need to copy your `schema.gql` into your `dist` folder rather than relying on the `autoSchemaFile` option since this tries to write to `/src` directory inside a running lambda function and you are only allowed to write to `/tmp` directory. You can modify your build script in your `package.json` to acheive this: |
There was a problem hiding this comment.
There's a spelling error: "acheive" should be "achieve".
| In addition to the above, when using NestJS with GraphQL in a lambda environment, you will need to copy your `schema.gql` into your `dist` folder rather than relying on the `autoSchemaFile` option since this tries to write to `/src` directory inside a running lambda function and you are only allowed to write to `/tmp` directory. You can modify your build script in your `package.json` to acheive this: | |
| In addition to the above, when using NestJS with GraphQL in a lambda environment, you will need to copy your `schema.gql` into your `dist` folder rather than relying on the `autoSchemaFile` option since this tries to write to `/src` directory inside a running lambda function and you are only allowed to write to `/tmp` directory. You can modify your build script in your `package.json` to achieve this: |
This PR updates the Readme with instructions on running with NestJS and with NestJS/GraphQL. This should also close out #115.
Checklist
npm run testandnpm run benchmarkand the Code of conduct