Shared Handlers

In using the Serverless framework, is it possible to have shared handlers?

If you have multiple domains and there are some handlers that are shared across those domains, how would you reference them within the servlerless.yml file? We have common handlers where their functionality is different based on parameters passed in through the environment section of the serverless.yml file but cannot figure out how to reference them correctly through the serverless.yml file, more specifically, the handler entry.

I have tried entries such as:

retrieveFoo:
  handler: common/common_retrieve.retrieve

and the directory structure looks like this

common:
  common_retrieve.js

fooA:
  serverless.yml <- retrieveFoo defined here
  other_functions.js

However, this does not seem to work.

I took a look at Function handler from folder outside project but there was no joy there, I would receive an error stating: No matching handler found for ‘common/common_retreive’ when I did a ‘serverless deploy’.

1 Like

Got the same question!..

By default, only files inside your service directory get packaged for deployment.

However, this seems to be a common practice to help keep things DRY and somebody has already written a handy plugin to help include external files when you deploy. Here’s what you can do:

$ npm install serverless-package-external --save-dev

Then in your serverless.yml file:

plugins:
  - serverless-package-external

custom:
  packageExternal:
    external:
      - "../common"

functions:
  retrieveFoo:
    handler: common/common_retrieve.retrieve.js

This tells serverless to include the common directory in your deployment package and copies it to the root of your fooA service directory. So the final package structure looks like this:

fooA/
  common/ 
    common_retrieve.js
  serverless.yml
  other_functions.js

Now you only have your common/ code written in a single location, and any service can get those files at deployment and use them.

1 Like