← Back
express gist typescript

express-typescript boilerplate

Init project #

echo {} > package.json
echo build/ >> .gitignore
git init .
npm i --save express
npm i -D typescript @types/express @types/node nodemon ts-node

Add scripts #

package.json:

{
"private": true,
"scripts": {
"dev": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/server.ts",
"build": "tsc",
"start": "node build/server.js"
},
"dependencies": {
...
},
"devDependencies": {
...
}
}

Add Typescript #

Add Typescript compiler configuration:

tsconfig.json:

{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "build",
"baseUrl": ".",
"paths": {
"*": ["node_modules/*", "src/types/*"]
}
},
"include": ["src/**/*"]
}

Basic structure #

mkdir src
touch src/config.ts
touch src/app.ts
touch src/server.ts

Add config file:

src/config.ts:

export const PORT = process.env.PORT || "3000";

Create the express application:

src/app.ts:

import express from "express";
const app = express();

app.get("/", (req, res) => {
res.json({ ready: true });
});

export default app;

Create a server:

src/server.ts:

import app from "./app";
import { PORT } from "./config";

app.listen(PORT, (err) => {
if (err) return console.error(err);
return console.log(`Server is listening on http://localhost:${PORT}`);
});

Essential middleware #

npm i --save cors helmet body-parser
npm i -D @types/cors @types/helmet

src/app.ts:

import express from "express";
import cors from "cors";
import helmet from "helmet";
import bodyParser from "body-parser";

const app = express();

app.use(helmet());
app.use(cors());
app.use(bodyParser.json());

export default app;

Error handler #

npm i --save @uphold/http-errors

src/app.ts:

import { ENV } from "./config";

app.use(function (err, req, res, next) {
if (ENV === "development") {
console.log("ERROR", err.toString());
console.log("STACK", err.stack);
}
res.status(err.status || 500).send(err.toString());
});

More #