Giter Site home page Giter Site logo

jdizm / node-express-backend-component Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 642 KB

A simple starter template for a backend API with Node, Express, TypeScript, Prisma, MongoDB. Authentication with Firebase with role based permissions. Deployment via DigitalOcean docker registry.

JavaScript 4.44% TypeScript 94.28% Dockerfile 1.27%
api backend express node template prisma typescript zod ts tsx pkgroll cicd digitalocean firebase github-actions gcp

node-express-backend-component's Introduction

node-express-backend-component

A simple node/express backend api template.

Requirements

This project requires node.js to be installed. This project uses volta to manage node versions.

To install volta run the following command in the terminal.

curl https://get.volta.sh | bash

This will require a mongodb database to be setup. You can set one up at https://cloud.mongodb.com/

This project also uses firebase auth for authentication. You can set one up at https://firebase.google.com/ and deployment is handled with DigitalOcean. See the authentication and deployment sections for more info.

ESM Node

https://www.typescriptlang.org/docs/handbook/esm-node.html

This project has been setup to use ESM Node. This allows us to use ES6 imports in Node.

This uses tsx as a dev server and pkgroll to bundle and build the project.

Note: Prisma does not support ESM by default and have an open issue -- looking to migrate this to another ORM (drizzle) for ESM support.

"the Prisma client relies on globals like __dirname that used to be part of Node but in ESM have been moved to import.meta.dirname. See: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules"

As a result of this it's best to stick to the .cjs format when running in production.

Setup

# install dependencies
npm i

# start the dev server
npm run dev

# view it running on localhost
curl localhost:3000

Be sure to configure the .env file with the correct values and make sure you have a mongodb database setup and firebase application credentials.

Testing

This project uses vitest for testing.

  1. run the unit tests with npm run test

It's also recommended to install the vitest extension for vscode.

Build with docker

locally

The GOOGLE_APPLICATION_CREDENTIALS env variable is mapped to the docker container from your home directory. This is required for the firebase admin sdk to verify the token and decode the claims. see the Firebase Auth section for more info on the service account key file and Google Application Credentials.

docker compose up -d

production

# build the app
npm run build

# build with docker
docker build . --tag node-express

# or to build with a specific platform
docker build . --tag node-express --platform linux/amd64

# start the docker container
docker run -d -p 3000:3000 node-express

# view it running on localhost
curl localhost:3000

When building with Docker locally it will require the service account key in the project root; this is because the Dockerfile is copying the service account key file into the image. See the Firebase Auth section for more info on the service account key file and Google Application Credentials.

Database

This is setup to use MongoDB with Prisma. If you want to use a different database you can change the db provider in Prisma schema and use a different Database.

Note: when using Prisma the MongoDB database connector uses transactions to support nested writes. Transactions require a replica set deployment. The easiest way to deploy a replica set is with Atlas. It's free to get started.

https://www.prisma.io/docs/concepts/database-connectors/mongodb

env

create a .env file in the root of the project and copy the contents of .env.example into it.

You can replace DATABASE_URL with your mongodb connection string whether that be cloud or locally hosted.

seed the db

run the seed script to seed the db the first time.

npx prisma db seed

updating db schema

# after updating the model you want to generate the schema
npx prisma generate

Import aliases

Aliases can be configured in the import map, defined in package.json#imports.

see: https://github.com/privatenumber/pkgroll#aliases

Authentication

This project uses JWT bearer token for authentication. The claims, id and sub must be set on the token and the token can be verified and decoded using the configured auth provider.

You can sign in an retrieve user tokens without having to use the client sdk.

See the Firebase REST API docs for more info on how to sign in with email and password.

Sign in with email and password is supported out of the box with Firebase Auth.

# sign in with email and password by posting
https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[API_KEY]

Permissions

How permissions work.

A resource will have a permission level. A user will have a role/claim.

Routes will have their permission level defined in ./src/helpers/permissions.ts

When a user makes a request to a route the route will check the user's role/claim against the permission level of the resource.

Permissions for the user can be set using the /auth/set-permissions endpoint which sets the database userId and claims on the firebase user. The token will have access to this data to verify the user's permissions.

Route permission levels

  1. Owner - Route can only be accessed by the owner of the resource. Defined by the id of the resource being accessed matching the id of the user making the request.
  2. User - Can access all resources with user permissions.
  3. Admin - Can access all resources.

Claims

A claim is defined when the user is created which defines the user's role and permissions level.

  1. User - default user permissions
  2. Admin - admin permissions

Firebase Auth

This project uses Firebase Auth for authentication. The firebase admin sdk is used to verify the token and decode the claims.

Because we are not running in a google environment we need to initialize the firebase admin sdk with a service account key file.

This requires a service account key file at $HOME/gcloud.json. The GOOGLE_APPLICATION_CREDENTIALS env variable must be set to the path of the service account key file.

You can create a service account from the firebase console and place in your home directory and set the environment variable like so:

export GOOGLE_APPLICATION_CREDENTIALS=$HOME/gcloud.json

When running in CI/CD the service account key file is stored as a secret and the env variable is set in the Dockerfile using the copied service account key file fron secrets.

Deployment with DigitalOcean

A docker image can be built and deployed to a container registry. We can configure DigitalOcean to deploy the image once the registry updates using their App Platform

The following secrets will need to be added to Github Actions for a successful deployment to DigitalOcean.

  • DIGITALOCEAN_ACCESS_TOKEN https://docs.digitalocean.com/reference/api/create-personal-access-token/
  • REGISTRY_NAME eg registry.digitalocean.com/my-container-registry
  • SERVICE_ACCOUNT_DEV The GOOGLE_APPLICATION_CREDENTIALS Service Account file for development env.
  • SERVICE_ACCOUNT_PROD The GOOGLE_APPLICATION_CREDENTIALS Service Account file for production env.
  • IMAGE_NAME_DEV the name of the DEV image we are pushing to the repository eg express-api it will be tagged with the latest version and a github sha.
  • IMAGE_NAME_PROD the name of the PROD image we are pushing to the repository eg express-api it will be tagged with the latest version and a github sha.

node-express-backend-component's People

Contributors

jdizm avatar renovate[bot] avatar

Stargazers

 avatar

Watchers

 avatar

node-express-backend-component's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

docker-compose
docker-compose.yml
dockerfile
Dockerfile
  • node 20-alpine
github-actions
.github/workflows/main.yml
  • actions/checkout v4
  • volta-cli/action v4
.github/workflows/pull-request.yml
  • actions/checkout v4
  • volta-cli/action v4
.github/workflows/release.yml
  • actions/checkout v4
  • volta-cli/action v4
npm
package.json
  • @prisma/client ^5.2.0
  • @types/cors ^2.8.17
  • @types/node ^20.2.1
  • @types/bcrypt ^5.0.0
  • @types/express ^4.17.17
  • bcrypt ^5.1.1
  • cors ^2.8.5
  • express ^4.18.2
  • firebase-admin ^12.0.0
  • mongodb ^6.3.0
  • pino ^8.15.1
  • pino-http ^9.0.0
  • @typescript-eslint/eslint-plugin ^7.0.0
  • @typescript-eslint/parser ^7.0.0
  • @vitest/coverage-v8 ^1.2.1
  • dotenv ^16.3.1
  • eslint ^8.37.0
  • eslint-config-prettier ^9.0.0
  • eslint-import-resolver-typescript ^3.5.5
  • eslint-plugin-import ^2.27.5
  • pkgroll ^2.0.0
  • prettier ^3.0.0
  • prisma ^5.2.0
  • tsx ^4.0.0
  • typescript ^5.0.4
  • vitest ^1.2.1
  • zod ^3.21.4
  • zod-prisma-types ^3.0.0
  • @rollup/rollup-linux-x64-gnu ^4.9.6
  • node 20.13.1

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.