Preparing Dev Environment for Lambda Function Urls
Before deploying the Lambda function urls, it's good to prepare the development environment to be able to test it locally. Despite AWS tools which I find a bit complicated, I just use a simple express server with request/response proxies for local testing. You need to import your lambda handler (which is main
) in this example. Here is the code for the express server:
// dev.ts
import "dotenv/config";
import { main } from "./app";
import express, { Application, Request, Response } from "express";
import { APIGatewayProxyEventV2 } from "aws-lambda";
import { randomUUID } from "crypto";
import cors from "cors";
const app: Application = express();
app.use(express.json());
app.use(cors());
const port = 9003;
async function proxyResponse(req: Request, res: Response) {
const proxyEvent = makeAWSProxyEvent(req);
const proxyResponse = await main(proxyEvent);
const response = { ...proxyResponse, body: JSON.parse(proxyResponse.body) };
res.send(response);
}
app.get("*", proxyResponse).post("*", proxyResponse).put("*", proxyResponse);
app.listen(port, () => {
console.log(`Devx API listening on port ${port}`);
});
function makeAWSProxyEvent(req: Request): APIGatewayProxyEventV2 | any {
const result = {
version: "1",
routeKey: "string",
rawPath: "string",
rawQueryString: "string",
cookies: req.cookies,
requestId: randomUUID(),
headers: req.headers,
queryStringParameters: req.query,
requestContext: {
http: {
path: req.path,
},
},
body: req.body,
};
return result;
}
By running this dev.ts
file, it'll start a server on port 9003. You can test your lambda function urls by sending requests to this server.