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"
}'
- 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
(That was before moving to TypeScript)
- 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 init
- Create
.gitignore
(Inspiration here)
- 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"
inpackage.json
) - Test it:
npm run test:unit
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"
inpackage.json
) - Test it:
npm run test:int
- 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
- 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 (Seeoverrides
section in.eslintrc.cjs
) - Add two npm scripts
"eslint"
and"eslint:fix"
- Test it:
npm run eslint
npm i pino
npm i pino-pretty -D
- Create the config you wish such as in
src/logger.js
- 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.