This is a very minimal setup with Typescript, Express.js and Zod, to demonstrate how we can use validation in our requests.
- Install everything:
npm install - Setup basic
.envfile:echo PORT=3000 > .env - Start the app:
npm start
Here are the endpoints and routes available for this app:
GET /errors/not-found- returns a 404GET /errors/async-example- calls an async function that throws an exceptionGET /errors/server-unavailable- returns a 500POST /users/function- example of validation with Zod using a functionPOST /users/middleware- example of validation with Zod using middleware
Previously I used ts-node-dev, however that tool is unreliable. There are many different ways of setting up a Typescript node project that reloads on change, as described in the StackOverflow answer How to watch and reload TS Node when Typescript files change, and in the end I went with swc + ts-node + nodemon, which was setup like this:
- Install
nodemon:npm install --save-dev nodemon - Install
ts-nodeandswc:npm install --save-dev ts-node @swc/core @swc/helpers regenerator-runtime - Add
swctotsconfig.json:
{
"compilerOptions": {
...
},
"ts-node": {
"swc": true
}
}
- Run with
nodemon:nodemon --watch src src/index.ts