Middy: [TypeScript] Documentation/Examples for writing custom middleware

Created on 3 Aug 2019  路  5Comments  路  Source: middyjs/middy

First, thanks for this library. You almost saved me from writing boilerplate code. I have a self inflicted problem - I decided on using typescript for my lambda functions and I have a use case to write custom middleware to take the idToken/JWT from Authorization header and then decode it to get the user name which will be used in my business logic.

Unfortunately, there aren't any examples of middlewares written in pure typescript in the repo. I went through the definitions and also the github issues trying to whip up one but failing miserably. Part of the problem is I am very new to typescript. It would be awesome if you can add a non-trivial example of writing a custom middleware in pure typescript in the repo. I can use that to write mine and probably contribute back what I am doing upstream. Decoding JWT from Cognito idToken and getting the user name seems like something that'd be useful.

documentation type-systems

Most helpful comment

I have written multiple middy middlewares in TypeScript which might help to inspire:
https://github.com/dbartholomae/middy-middleware-jwt-auth (works fine in production)
https://github.com/dbartholomae/middy-middleware-class-validator (not tested yet in production)
https://github.com/dbartholomae/middy-middleware-json-error-handler (not tested yet in production)

All 5 comments

Hello @lakshmi-kannan!
Thanks for using Middy :)

Unfortunately, I am not experienced with TypeScript to be able to provide a set of good examples. In any case, even by using TypeScript, you should be able to use plain JavaScript in your TypeScript projects, so, I believe, the examples here should work out of the box.

Let me know if you make any progress and if eventually, you would like to open a documentation PR to add this kind of examples.

@lmammino Thanks! I finally got a custom middleware written in Tyepscript and hooked it up to run before my handler and it works. Sample code below:

export function idTokenMiddleware(): MiddlewareObject<any, any> {
  return {
    before: async (
      handler: HandlerLambda<APIGatewayEvent, APIGatewayProxyResult>
    ): Promise<void> => {
      console.log('ID Token parse middleware');
      const headers: { [name: string]: string } = handler.event.headers || {};
      const authHeader: string = 'Authorization';

      if (authHeader in headers) {
        const bearerToken: string = headers.Authorization;
        const idTokenStr: string = parseBearerToken(bearerToken);
        if (idTokenStr) {
          const idToken: IdToken = await parseIdToken(idTokenStr);
          console.log(`id token - ${idToken}`);
          return;
        }
      }

      console.log('Done ID token parse middleware before.');
      return Promise.reject(undefined);
    }
  };
}

However, there are couple of issues

  1. I don't know how to pass the output from this async middleware to the handler. Reading through middy.js, it doesn't look like a return value from a middleware is fed into the next one. Is the assumption that middlewares are "stateless"? How can I pass a context object across all middlewares? Any particular examples?

  2. I don't like to cheat the MiddlewareObject with . The typescript definitions are a little confusing. Any ideas how I can avoid any, any?

Here is the complete code for the middleware https://gist.github.com/lakshmi-kannan/79a8878cbef9867856d588a3dfc4e1b2 Here is how I consume the middleware https://gist.github.com/lakshmi-kannan/8c52cec115b6ab471d1d6353b1d15942. I might open source it in a repo when I clean it up and figure out how to pass the middleware result as context.

So close! Appreciate your help!

Just needed more sleep and self-belief :).

  1. Apparently I just needed MiddlewareObject
  2. Mangling the AWS lambda context worked for me. I referred to the example in https://github.com/middyjs/middy/issues/275.

I'll look into opening a docs PR now.

I have written multiple middy middlewares in TypeScript which might help to inspire:
https://github.com/dbartholomae/middy-middleware-jwt-auth (works fine in production)
https://github.com/dbartholomae/middy-middleware-class-validator (not tested yet in production)
https://github.com/dbartholomae/middy-middleware-json-error-handler (not tested yet in production)

TypeScript has been updated in v2 beta, along with the addition of docs. Hope this helps.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wrumsby picture wrumsby  路  7Comments

lmammino picture lmammino  路  6Comments

dschep picture dschep  路  6Comments

willfarrell picture willfarrell  路  3Comments

chrisandrews7 picture chrisandrews7  路  6Comments