This is the example repository from the blog post 'Bulletproof node.js project architecture'
Please read the blog post in order to have a good understanding of the server architecture.
Also, I added lots of comments to the code that are not in the blog post, because they explain the implementation and the reason behind the choices of libraries and some personal opinions and some bad jokes.
The API by itself doesn't do anything fancy, it's just a user CRUD with authentication capabilities. Maybe we can transform this into something useful, a more advanced example, just open an issue and let's discuss the future of the repo.
We use node
version 14.9.0
nvm install 14.9.0
nvm use 14.9.0
The first time, you will need to run
npm install
Then just start the server with
npm run start
It uses nodemon for livereloading :peace-fingers:
You can use Gitpod for the one click online setup. With a single click it will launch a workspace and automatically:
bulletproof-nodejs
repo.cp .env.example .env
.npm run start
.By using celebrate, the req.body schema becomes cleary defined at route level, so even frontend devs can read what an API endpoint expects without needing to write documentation that can get outdated quickly.
route.post('/signup',
celebrate({
body: Joi.object({
name: Joi.string().required(),
email: Joi.string().required(),
password: Joi.string().required(),
}),
}),
controller.signup)
Example error
{
"errors": {
"message": "child \"email\" fails because [\"email\" is required]"
}
}
Read more about celebrate here and the Joi validation API
To simplify documenting your API, we have included Optic. To use it, you will need to install the CLI tool, and then you can use api exec "npm start"
to start capturing your endpoints as you create them. Once you want to review and add them to your API specification run: api status -- review
.
It's not a good idea to have node.js serving static assets a.k.a the frontend
Also, I don't wanna take part in frontend frameworks wars π
Just use the frontend framework you like the most or hate the least. It will work π
I know this is not a perfect architecture but it's the most scalable that I know with less code and headache that I know.
It's meant for small startups or one-developer army projects.
I know if you start moving layers into another technology, you will end up with your business/domain logic into npm packages, your routing layer will be pure AWS Lambda functions and your data layer a combination of DynamoDB, Redis, maybe redshift, and Agolia.
Take a deep breath and go slowly, let the business grow and then scale up your product. You will need a team and talented developers anyway.