Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@tsndr/aws-lambda-router

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tsndr/aws-lambda-router

AWS Lambda Router is a super lightweight router (2.30 KiB) with middleware support and **ZERO dependencies** for [AWS Lambda](https://aws.amazon.com/lambda/).

  • 1.0.5
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

AWS Lambda Router

AWS Lambda Router is a super lightweight router (2.30 KiB) with middleware support and ZERO dependencies for AWS Lambda.

I worked a lot with Express.js in the past and really enjoyed their middleware approach.

This is a port of @tsndr/cloudflare-worker-router.

Contents

Usage

Simple Example

import Router from '@tsndr/aws-lambda-router'

// Initialize router
const router = new Router()

// Enabling buildin CORS support
router.cors()

// Register global middleware
router.use(({ req, res, next }) => {
  res.headers.set('X-Global-Middlewares', 'true')
  next()
})

// Simple get
router.get('/user', ({ req, res }) => {
  res.body = {
    data: {
      id: 1,
      name: 'John Doe'
    }
  }
})

// Post route with url parameter
router.post('/user/:id', ({ req, res }) => {

  const userId = req.params.id
  
  // Do stuff...
  
  if (errorDoingStuff) {
    res.status = 400
    res.body = {
      error: 'User did stupid stuff!'
    }
    return
  }
  
  res.status = 204
})

// Delete route using a middleware
router.delete('/user/:id', ({ req, res, next }) => {

  if (!apiTokenIsCorrect) {
    res.status = 401
    return
  }
  
  await next()
}, ({ req, res }) => {

  const userId = req.params.id
  
  // Do stuff...
})

// Listen AWS API Gateway Event
export const handler = (event, context) => {
  return router.handle(event, context)
}

Reference

router.debug([state = true])

Enable or disable debug mode. Which will return the error.stack in case of an exception instead of and empty 500 response. Debug mode is disabled by default.

state

State is a boolean which determines if debug mode should be enabled or not (default: true)

router.use([...handlers])

Register a global middleware handler.

handler(ctx)

Handler is a function which will be called for every request.

ctx

Object containing env, req, res, next

router.cors([config])

If enabled will overwrite other OPTIONS requests.

config (object, optional)
KeyTypeDefault Value
allowOriginstring*
allowMethodsstring*
allowHeadersstring*
maxAgeinteger86400
optionsSuccessStatusinteger204

router.any(url, [...handlers])

router.connect(url, [...handlers])

router.delete(url, [...handlers])

router.get(url, [...handlers])

router.head(url, [...handlers])

router.options(url, [...handlers])

router.patch(url, [...handlers])

router.post(url, [...handlers])

router.put(url, [...handlers])

router.trace(url, [...handlers])

url (string)

The URL starting with a /. Supports the use of dynamic parameters, prefixed with a : (i.e. /user/:userId/edit) which will be available through the req-Object (i.e. req.params.userId).

handlers (function, optional)

An unlimited number of functions getting req and res passed into them.

ctx-Object

KeyTypeDescription
envobjectEnvironment
reqreq-ObjectRequest Object
resres-ObjectResponse Object
nextnext-HandlerNext Handler

req-Object

KeyTypeDescription
bodyobject / stringOnly available if method is POST, PUT, PATCH or DELETE. Contains either the received body string or a parsed object if valid JSON was sent.
headersobjectRequest Headers Object
methodstringHTTP request method
paramsobjectObject containing all parameters defined in the url string
queryobjectObject containing all query parameters

res-Object

KeyTypeDescription
bodyobject / stringEither set an object (will be converted to JSON) or a string
headersobjectResponse Headers Object
statusintegerReturn status code (default: 204)
webSocketWebSocketUpgraded websocket connection

Setup

npm i -D @tsndr/aws-lambda-router

and replace your index.ts / index.js with one of the following scripts

TypeScript (src/index.ts)
import Router from '@tsndr/aws-lambda-router'

const router = new Router()

// TODO: add your routes here

export const handler: APIGatewayProxyHandlerV2<APIGatewayProxyEventV2> = (event, context) => {
    return router.handle(event, context)
}
JavaScript (src/index.js)
import Router from '@tsndr/aws-lambda-router'

const router = new Router()

// TODO: add your routes here

export const handler = (event, context) => {
  return router.handle(event, context)
}

Keywords

FAQs

Package last updated on 25 Aug 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc