0

I have an application that runs as AWS Lambda function using Cognito authentication. It all works fine but now I am attempting to optimise the bundle size to reduce cold start times.

The process of verifying and decoding the JWT involves:

  • Fetch JWK from internal AWS endpoint
  • Call jwkToPem from jwk-to-pem module
  • Verify and decode JWT using jsonwebtoken module

When I look at the node_modules in my archive, the largest packages are all related to the steps above:

elliptic 140kb
bn.js 108kb
jsonwebtoken 84kb
hash.js 80kb
asn1.js 72kb
hmac-drbg 36kb
jwk-to-pem 32kb

Total ~550kb

This is over half of node_modules size and my application code is just 164kb un-minified, so as you can see the JWT decode has a substantial impact on overall bundle size.

Am wondering if there is a lighter weight alternative...

Thanks for any suggestions

jugglingcats
  • 698
  • 9
  • 29

1 Answers1

1

Given that the "Fetch JWK from internal AWS endpoint" step is fetching from a JSON Web Key Set, the jose version 3.x module can do everything for you.

The disk size is bigger, but that's because it's a universal module and bundles runtime also for the web, in both esm and cjs flavours, but don't fret - in your runtime it requires only the node runtime files and has 0 dependencies. And you can use rollup to tree-shake all of the weight you're not using (other submodules and runtime files).

import jwtVerify from 'jose/jwt/verify'
import createRemoteJWKSet from 'jose/jwks/remote'

const JWKS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'))

const { payload, protectedHeader } = await jwtVerify(token, JWKS, {
  issuer: 'urn:example:issuer',
  audience: 'urn:example:audience'
})
  • Sounds good thanks, but I tried running rollup on my entry file and it just output the file more or less unchanged, it didn't bundle or tree shake anything. Is there a one-liner that will make rollup do what you suggest or do I need to configure one or more plugins? A link to the basic steps would be really useful. Tx again – jugglingcats Feb 06 '21 at 07:32
  • esbuild can do it too. I use it in jose's test suite to make a tree shaken browser bundle. https://github.com/panva/jose/blob/08b16d318325f928068b417c0282b1a54b7f0708/package.json#L345 –  Feb 06 '21 at 08:41
  • Thanks esbuild looks promising! – jugglingcats Feb 06 '21 at 13:02
  • My entire lambda package archive is now 21kb... amazing! Still working through making sure everything is working but looks like it is... thank you. – jugglingcats Feb 06 '21 at 19:20