Skip to content

Instantly share code, notes, and snippets.

@ofhouse
Last active January 4, 2021 14:44
Show Gist options
  • Save ofhouse/e5455254983f0f5e9aa07e55552c079b to your computer and use it in GitHub Desktop.
Save ofhouse/e5455254983f0f5e9aa07e55552c079b to your computer and use it in GitHub Desktop.
Reference implementation how to start a Next.js webserver inside a Lambda from API Gateway invocation
// Reference implementation how to start a Next.js webserver inside a Lambda
// from API Gateway invocation
// https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
const { request } = require('http');
// Import the generated Next.js server from somewhere
const NextServer = require('./dist');
exports.handler = async function (event) {
// Deconstruct API Gateway event
const {
http: { method, path },
} = event.requestContext;
// Start local server and get address once it's running
const address = await new Promise((resolve) => {
const server = new NextServer();
server.listen(
{
host: '127.0.0.1',
port: 0,
},
function listeningCallback() {
const addr = this.address();
resolve(addr);
}
);
});
const payload = await new Promise((resolve, reject) => {
request(
{
hostname: '127.0.0.1',
port: address.port,
path,
method,
},
(res) => {
const respBodyChunks = [];
res.on('data', (chunk) => respBodyChunks.push(Buffer.from(chunk)));
res.on('error', reject);
res.on('end', () => {
const bodyBuffer = Buffer.concat(respBodyChunks);
resolve({
statusCode: response.statusCode || 200,
headers: response.headers,
body: bodyBuffer.toString('base64'),
isBase64Encoded: true,
});
});
}
);
});
return payload;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment