NAV Navbar
javascript
  • Introduction
  • Installation
  • Instantiation
  • Creating routes
  • Callback functions
  • Retrieve parameters
  • API Gateway Configuration
  • Introduction

    Welcome to the AWSLambdaRouter documentation!

    AWSLambdaRouter is a simple HTTP router inspired by Express.js router's syntax. It allows you to transfer your stateless Express application to an AWS Lambda using the proxy integration of AWS API Gateway.

    Installation

    npm install aws-lambda-router-wn --save

    Instantiation

    const AWSLambdaRouter = require('aws-lambda-router-wn');
    const app = new AWSLambdaRouter();
    
    // declare your routes here
    
    exports.handler = (event, context, callback) => {
      app.serve(event, callback);
    };
    

    This is the basic implementation of the AWSLambdaRouter.

    The constructor does not require any parameters as it only instantiate an AWSLambdaRouter object. The serve function receives directly the event and the callback from the AWS Lambda handler.

    You should not have to alter this basic configuration. to use the AWSLambdaRouter.

    Creating routes

    Of course this basic configuration won't do anything without any route declaration.

    As AWSLambdaRouter is inspired by Express.js, we tried to keep a syntax already known by thousands of developers.

    GET methods

    const AWSLambdaRouter = require('aws-lambda-router-wn');
    const app = new AWSLambdaRouter();
    
    app.get('/', (request, response) => {
      response(null, {text: 'hello world'});
    });
    
    app.get('/todo', (request, response) => {
      // getAllTodos is a fictional function, just for the example
      const todos = getAllTodos();
      response(null, {todos: todos});
    });
    
    exports.handler = (event, context, callback) => {
      app.serve(event, callback);
    };
    

    By default, AWSLambdaRouter response type is 'application/json'

    The get function takes a path and a callback function as parameters.

    The callback function must be able to receive a request object and a response function.

    POST methods

    app.post('/todo/add', (request, response) => {
      const todo = request.body.todo;
      const newTodo = insertTodo(todo);
      response(null, {status: 'todo added', todo: newTodo.id});
    });
    

    By default, AWSLambdaRouter will expect request's Content-Type to be 'application/json'

    The post function also takes a path and a callback function as parameters.

    As for the get function, the callback function must be able to receive a request object and a response function.

    The body parameters are accessible from the request.body variable.

    DELETE methods

    app.delete('/todo', (request, response) => {
      const todo = request.body.todo;
      deleteTodo(todo);
      response(null, {status: 'todo deleted'});
    });
    

    The delete function also takes a path and a callback function as parameters.

    As for the get function, the callback function must be able to receive a request object and a response function.

    The body parameters are accessible from the request.body variable.

    Other methods

    app.route('PUT', '/todo/batch', (request, response) => {
      const todos = request.body.todos;
      const newTodos = insertLoadsOfTodos(todos);
      response(null, {status: 'todos inserted', todos: newTodos});
    });
    

    You can also use the route function to declare your route.

    The route function takes a method, a path and a callback function as parameters.

    Method is not case sensitive; e.g. you can write post or POST.

    The callback function must be able to receive a request object and a response function.

    The body parameters are accessible from the request.body variable.

    Supported paths

    app.get('/', (request, response) => {
      response(null, {text: 'hello world'});
    });
    app.get('/example', (request, response) => {
      response(null, {text: 'hello world'});
    });
    app.get('/example/hello/world', (request, response) => {
      response(null, {text: 'hello world'});
    });
    

    Here are some examples of the paths you can use to declare your route.

    Callback functions

    Every routes must have a callback function. This function will be executed if the event's path and method match one the AWSLambdaRouter route declaration.

    The callback function must accept a request object and a response function as parameters.

    Request object

    Example of a raw request object

    {
        "resource": "/",
        "path": "/",
        "httpMethod": "POST",
        "headers": {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Authorization": "Bearer *************",
            "cache-control": "no-cache",
            "CloudFront-Forwarded-Proto": "https",
            "CloudFront-Is-Desktop-Viewer": "true",
            "CloudFront-Is-Mobile-Viewer": "false",
            "CloudFront-Is-SmartTV-Viewer": "false",
            "CloudFront-Is-Tablet-Viewer": "false",
            "CloudFront-Viewer-Country": "GB",
            "Content-Type": "application/json",
            "Custom-Header": "thisisacustomheader",
            "Host": "******.execute-api.eu-west-1.amazonaws.com",
            "Postman-Token": "ce28c4b2-9c45-48f2-8793-8ab1ff0bc25c",
            "User-Agent": "PostmanRuntime/6.4.1",
            "Via": "1.1 *****.cloudfront.net (CloudFront)",
            "X-Amz-Cf-Id": "*******",
            "X-Amzn-Trace-Id": "********",
            "X-Forwarded-For": "**.**.**.**, **.**.**.**",
            "X-Forwarded-Port": "443",
            "X-Forwarded-Proto": "https"
        },
        "queryStringParameters": {
            "test1": "hello",
            "test2": "world"
        },
        "pathParameters": null,
        "stageVariables": null,
        "requestContext": {
            "path": "/prod",
            "accountId": "*******",
            "resourceId": "******",
            "stage": "prod",
            "requestId": "******",
            "identity": {
                "cognitoIdentityPoolId": null,
                "accountId": null,
                "cognitoIdentityId": null,
                "caller": null,
                "apiKey": "",
                "sourceIp": "**.**.**.**",
                "accessKey": null,
                "cognitoAuthenticationType": null,
                "cognitoAuthenticationProvider": null,
                "userArn": null,
                "userAgent": "PostmanRuntime/6.4.1",
                "user": null
            },
            "resourcePath": "/",
            "httpMethod": "POST",
            "apiId": "*******"
        },
        "body": "{\n\t\"data\": [\n\t\t{\n\t\t\t\"foo\":\"bar\"\n\t\t}\n\t]\n}",
        "isBase64Encoded": false
    }
    

    The request object will contain any information you need from the request receive by API Gateway and transferred to your Lambda.

    The things you'll probably need are: 1. request.queryStringParameters 2. request.body 3. request.headers

    Response function

    app.get('/', (request, response) => {
      response(null, {text: 'hello world'});
    });
    
    app.get('/forced-error', (request, response) => {
      response(new Error('This is an error message'), null);
    });
    
    app.get('/index', (request, response) => {
      response(null, `
    <!DOCTYPE html>
      <html>
        <head>
          <meta charset="UTF-8">
          <title>title</title>
        </head>
        <body>
          <h1>A random website</h1>
        </body>
     </html>
    `);
    }, {
      responseType: 'text/html'
    });
    

    The response function takes two parameters.

    Parameter Description
    error A JavaScript Error object, should be null if the request is successful.
    data The data that will be sent in the HTTP response. Can be a JavaScript object, as well a String.

    Options

    app.route('POST','/foo', (request, response) => {
      const param = request.body;
      response(null, `<div>foo:${param.foo}</div>`);
    }, {
      bodyType: 'application/x-www-form-urlencoded',
      responseType: 'text/html'
    });
    

    The functions get, post, delete, and route, can take an additional, optional parameters: options.

    The options parameters should be a JavaScript object. Here are the available options.

    Parameter Default Description
    bodyType application/json Sets the expected Content-Type of the request received for thie route.
    responseType application/json Sets the Content-Type of the response for this route.

    Retrieve parameters

    Query string parameters

    // When GET /example?id=1&name=John is sent
    
    app.get('/example', (request, response) => {
      const id = request.queryStringParameters.id;
      const name = request.queryStringParameters.name;
      response(null, {text: `Hello ${name}`}); //'Hello John'
    });
    

    In the callback function, you can retrieve query string parameters in the request.queryStringParameters object. You don't need to specify the parameters that will be required in the route configuration.

    Body parameters

    app.post('/example', (request, response) => {
      const id = request.body.id;
      const name = request.body.name;
      response(null, {text: `Hello ${name}`}); //'Hello John'
    });
    
    app.post('/example/form', (request, response) => {
      const id = request.body.id;
      const name = request.body.name;
      response(null, {text: `Hello ${name}`}); //'Hello John'
    }, {
      bodyType: 'application/x-www-form-urlencoded'
    });
    

    In the callback function, you can retrieve query string parameters in the request.body object.

    Depending on the Content-Type of the request receive by API Gateway and by the Lambda, you might want to change the bodyType options.

    Request headers

    app.get('/', (request, response) => {
      const headers = request.headers;
      response(null, {text: 'hello world'});
    });
    

    In the callback function, you can retrieve headers in the request.body object.

    API Gateway Configuration

    1. First, create a new API on AWS API Gateway (it's important that you use 1 API for 1 AWSLambdaRouter).
    2. You should have a '/' route with no methods configured, create a new resource using the actions button.
    3. Click on configure as proxy resource and leave the field as they are, enable the CORS configuration if you wish (this will add OPTIONS route). You should have something similar to the image below: proxy resource
    4. Click on create, you should be redirect to the configuration of the ANY method, configure it as a Lambda proxy, and enter the name of your lambda, like below: any setup
    5. Click on save, select the '/' route and click on the actions button to create a new ANY method (this time for the '/' route, not '/{proxy+}'.
    6. Configure the new ANY method like the previous one.
    7. Enable CORS on the '/' route if needed.
    8. In the end, you should have something similar for your two ANY method, like this image below: final
    9. Use the actions button to deploy your API.