Skip to content
/ node-api-starter Public template

Simple starting point to create a Node.js API

License

Notifications You must be signed in to change notification settings

cedric25/node-api-starter

Repository files navigation

node-starter

Simple starting point to create a Node.js API with fastify.

Includes:

  • Two endpoints: / (GET + POST)
  • Tests with jest
  • Code style with Prettier
  • Code quality with ESLint
  • Logs with pino
  • Environment variables wit dotenv

Test POST endpoint:

curl -X POST \
  http://localhost:3000/ \
  -H 'Content-Type: application/json' \
  -d '{
    "hello": "world"
}'

How to use

  • Clone this project
git clone https://github.com/cedric25/node-api-starter.git my-api
cd my-api
nvm use
npm i
  • Remove git history and create your own:
rm -rf .git
git init
git add .
git commit -m ":zap: Init project"
  • Run server
npm start
or  
npm run dev  
or  
npm run dev:debug
  • Run tests
npm t

Steps done to create this project

(That was before moving to TypeScript)

App

  • Check your node version: LTS or Current (https://nodejs.org/) (Use fnm, nvm or n)
  • Create a new folder and run npm init --yes
  • npm i fastify
  • Copy-paste a code sample from fastify 'Getting Started'
  • Create a npm script in package.json: "start": "node server"
  • Try it: npm start
  • In dev, you can use nodemon to run your server

Git

  • git init
  • Create .gitignore (Inspiration here)

Tests

Unit

  • Extract the 'app' logic of your server to src/app.js
  • Create a small test (./src/utils/utils.spec.js)
  • Add convenient npm script (See "test:unit" in package.json)
  • Test it: npm run test:unit

Integration

Made with fastify.inject()

  • Create a mocha options file: test/int/.mocharc.int.js
  • Create a setup file to start the server prior to the tests: test/int/setup.ts
  • Create a small test (./src/app.test.ts)
  • Add convenient npm scripts (See "test:int" and "test" in package.json)
  • Test it: npm run test:int

Prettier

  • Install Prettier
  • Create your .prettierrc file
  • Add two npm scripts "prettier": "prettier src --check" and "prettier:fix": "prettier src --write"
  • Test it: npm run prettier

ESLint

  • Install ESLint
  • Init a config file: npm init @eslint/config
  • Tell ESLint about Jest: npm i eslint-plugin-jest -D and use it for test files (See overrides section in .eslintrc.cjs)
  • Add two npm scripts "eslint" and "eslint:fix"
  • Test it: npm run eslint

Logs (pino)

  • npm i pino
  • npm i pino-pretty -D
  • Create the config you wish such as in src/logger.js

dotenv

  • Use dotenv with the .env file to set your environment variables for your local environment.

Also worth having a look at dotenv-flow and dotenv-flow-cli if for example you need non-committed env vars in a .env.local file.

About

Simple starting point to create a Node.js API

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published