How to Structure Serverless Framework Applications?

103 Views Asked by At

So, I'm new to serveless and have been trying to create a serverless backend for my project and scratching my head over the best way to organize things. Initially, I thought of laying it out like this:

|--src
|    |--auth-service
|    |--products
|    |--customers
|--package.json
|--serverless.yml

However, I quickly realized an issue – the node_modules folder. For instance, the auth section requires the bcrypt package, whereas the customers section does not. Deploying the same node_modules folder to every function includes unnecessary packages.
So, I came up with a different game plan:

|--customers
|    |--node_modules
|    |--handler.js
|    |--package.json
|    |--serverless.yml
|--products
|    |--node_modules
|    |--handler.js
|    |--package.json
|    |--serverless.yml
|--auth-service
|    |--node_modules
|    |--handler.js
|    |--package.json
|    |--serverless.yml

Here, the node_modules folder is not global but is scoped to contain only the packages required by each function.

With this setup, I have to deploy by running serverless deploy within each folder.

  • Question 1)
    A challenge remains – how do I configure "auth-service" (which has a function checking JWT) as an authorizer for the "customers" and "products" functions within their respective serverless.yml files? My initial thought was to use the ARN for the auth function and set it as the authorizer for all other functions, but I am not sure if this is a good approach

  • Question 2)
    Is there a better way to structure the project, especially since now deploying resourcing is a pain, for example if I want a dynamodb table, I should'nt be defining it as a resouce inside a particual functions serverless.yml file, right? So is there a way to kind to bundle all these different services, and maybe define resources in centralized place.

1

There are 1 best solutions below

0
qasimalbaqali On

The following is what I usually do as a practice, not sure if it is a best practice or not that is followed by many

  1. This is the way I would also do it. If I have a shared resource such as an authorizer, I would create it in a different service and then reference it in the different services that require such as what you're doing. So the way you're doing it IMO is fine

  2. If you mean what's the best place to define a shared resource, I would also have it in a place in a service that is not being touched (modified/redeployed) quite a lot just to be safe that no one make any modifications that might break it. Though, I would place it as close as possible to it's service that it relates to in the first place if there is any.

You might want to look into serverless-compose that can help you deploy multiple services at once instead of running sls deploy in each and orchestrate the deployment all together