DEV Community

Cover image for Create an NodeJs Server in Typescript
briankarlsayen
briankarlsayen

Posted on

Create an NodeJs Server in Typescript

If you're a beginner on typescript or some veteran who tends to forget how to setup a typescript server the you've come to the right place.

Here are the steps to create a typescript server up and running:

  • Make a folder then, initialize the node project
npm init -y
Enter fullscreen mode Exit fullscreen mode
  • Install dependencies, in this case I'm installing expressjs as my web app framework but feel free to use others like fastify
npm i express cors dotenv
npm i -D typescript @types/node @types/express concurrently
Enter fullscreen mode Exit fullscreen mode
  • Initialize tsconfig
npx tsc --init
Enter fullscreen mode Exit fullscreen mode
  • Edit tsconfig.json
"outDir": "./dist"
Enter fullscreen mode Exit fullscreen mode
  • Edit package.json scripts
"scripts": {
"build": "npm install typescript && npx tsc",
"start": "node dist/index.js",
"dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\""
}
Enter fullscreen mode Exit fullscreen mode
  • Create a file named index.ts, this will server as the root file for your server. Paste this inside index.ts.
import express, { Express } from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import http from 'http';
dotenv.config();

const app: Express = express();
const port = process.env.PORT ?? 5905;
app.use(cors());
const server = http.createServer(app);

server.listen(port, () => {
  console.log(`⚡️[server]: Server is running at http://localhost:${port}`);
});

Enter fullscreen mode Exit fullscreen mode
  • Run build
npm run build
Enter fullscreen mode Exit fullscreen mode
  • Finally run the server
npm run dev
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)