/backend-template

A backend template for general projects. This is the initial structure of a project. If you are trying to start a backend project with express, this kit is possible to minimize troublesome work.

Primary LanguageTypeScriptApache License 2.0Apache-2.0

Forks Stargazers Issues-open Issues-closed Contributors [Code Size[]

express-production-template
app-icon
Template for backends with NodeJS + Express, ready to use in production!
🐞 Report a bug or 🙋‍♂️ request a feature
contributions welcome License

Features

Framework javascript nodejs

  • Async/Await support
  • WinstonJs Logger Implementation
  • Error Handling
  • Postgres Migrations and Seed Support
  • Basic request parameters Validation
  • Open Api Specification implemented through swagger and swagger-ui
  • JWT implementation
  • Environment variables to hold configuration values .env file
  • Functional Programming with Middlewares and helpers
  • Standard Coding with Eslint and Prettier, this helps to keep thing into perspective.

JavaScript Style Guide

Tech Stack

Category Name
Language TypeScript
JS Runtime Node
Web Framework Express
Database PostgreSQL
ORM TypeORM
Test Framework Jest
Authentication JWT
Linter TSLint
Formatter Prettier

Getting started

How to use it

This code is meant to be run in a server accesible online, so other services can use it. This is a Rest Api solution using basic database create, read, update and delete operations (CRUD) as well as a basic token (JWT) generator/validator.

It uses a RESTful API to be used by any other client, but for human readability it also have swagger (it can even be used as an ad hoc admin panel!). To use it from a client you need to make HTPP(S) requests, for example using curl:

> curl http://localhost:8000/ping -v
> curl -d "email=example&password=example2" http://localhost:8000/api/v1/auth/login

But you can use any language or library: PHP, GO, C++, Rust, etc. The only unique point is how to manage the JWT. It was decided to use a header named x-access-token, in order to avoid a normal way to check for tokens: Authorization: Bearer header. This is just an extra security measure. To send a JWT token for a request in a protected endpoint, you MUST use x-access-token header.

Pre requirements

Before to start you need have some requirements:

  1. Node.js > v16.13.2

    Node.js is a runtime environment for Javascript that allows us to use the language outside of the browser, in this case we use it to configure and run the development server.

  2. npm > v8.1.2

    npm is a package manager for Node.js and comes installed with it, we use it to install and manage application dependencies.

  3. Git > v2.0.0

    Git is a version control system for code, we use it to manage the different branches of the code.

  4. Connection to internet

  5. Visual Studio Code or another code editor (optional)

Installation

To get the Node server running locally:

  • Clone this repo
  • npm install to install all required dependencies
  • npm run dev or npm run dev:dash (with GUI-like experience on your terminal) to start the local server

Set Environments

> cp .env.example .env
> nano .env

Remove local branches deleted on the remote server

> git fetch -p && for branch in `git branch -vv --no-color | grep ': gone]' | awk '{print $1}'`; do git branch -D $branch; done

Check unused, outdated states of dependencies: npx depcheck # OR npx npm-check-updates

Code Overview

This backend's code is made using JavaScript language, and Node.js runtime. With a package named Express.js to create the server, routers and middleware necessary. Also PostgreSQL is used to provide a modern, open sourced and performant database layer. Lastly, the server have auxiliar packages for development and deployment to ensure is production ready, enterprise level. Typing and compile correctness by Typescript.

As with most of node.js applications, we would want to install node and npm in our local PC in order to run the server or develop code. This folder include all the necessary files to run the server local or online, just take into account that you'll need to use a terminal as no GUI is available yet.

If you want to develop you have to setup a good dev environment. First of all a good text editor/IDE, I prefer to use Visual Studio Code, but you can use anything else. For the use of VSCode I provide configuration files in the hidden folder .vscode.

For more information about the code please check the code overview.

Dependencies

  • expressjs - The server for handling and routing HTTP requests
  • express-jwt - Middleware for validating JWTs for authentication
  • jsonwebtoken - For generating JWTs used by authentication
  • slug - For encoding titles into a URL-friendly format

Application Structure

  • app.js - The entry point to our application. This file defines our express server and connects it to MongoDB using mongoose. It also requires the routes and models we'll be using in the application.
  • routes/ - This folder contains the route definitions for our API.
  • models/ - This folder contains the schema definitions for our models.

Generating Migration

  • Auto generate : npm run typeorm migration:generate -- -n <migration-name>
  • Create empty file : npm run typeorm migration:create -- -n <migration-name>
  • Run migration : npm run typeorm migration:run
  • Revert migration : npm run typeorm migration:revert

Authentication

Requests are authenticated using the Authorization header with a valid JWT. We define two express middlewares in routes/auth.js that can be used to authenticate requests. The required middleware configures the express-jwt middleware using our application's secret and will return a 401 status code if the request cannot be authenticated. The payload of the JWT can then be accessed from req.payload in the endpoint. The optional middleware configures the express-jwt in the same way as required, but will not return a 401 status code if the request cannot be authenticated.

Collaborators

Israel Laguan email-icon Email me to contact@israellaguan.com / linkedin-icon Connect to my LinkedIn
author-pic banner
Victor Peña email-icon Email me to victordev2002@gmail.com / linkedin-icon Connect to my LinkedIn
victor-pic
Emmanuel Azócar email-icon Email me to azocarmel@gmail.com
emmanuel-pic
Angelica Molina email-icon Email me to angeli.molina1@gmail.com
ange-pic

References and kudos

Used:

https://medium.com/the-node-js-collection/simple-server-side-cache-for-express-js-with-node-js-45ff296ca0f0 https://github.com/nfour/eslint-config-standard-typescript-prettier https://codeql.github.com/ https://github.com/santoshshinde2012/node-boilerplate https://medium.com/@tadeaspetak/frontend-fullstack-security-298154016374 https://github.com/PW486/express-ts-starter // Have docker conf

Ideas

https://github.com/MichielDeMey/express-jwt-permissions https://www.medianova.com/en-blog/nodejs-exprees-for-jwt-auth-example/ https://siddharthac6.medium.com/json-web-token-jwt-the-right-way-of-implementing-with-node-js-65b8915d550e https://blog.appsignal.com/2021/02/03/improving-node-application-performance-with-clustering.html https://jasonwatmore.com/post/2018/08/06/nodejs-jwt-authentication-tutorial-with-example-api https://github.com/cham11ng/typescript-api-starter // Have migrations with Postgres https://caddyserver.com/docs/running

Contributing

contributions welcome

🤝 Contributions, issues and feature requests are welcome! Feel free to check the issues page.

Show your support

🤗 Give a ⭐️ if you like this project!

Icons from:

Icons8

License

License

📝 This project is licensed under the MIT
Feel free to fork this project and improve it