Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save barinascode/5c7c01dfe179b01577eb6771f27a3297 to your computer and use it in GitHub Desktop.
Save barinascode/5c7c01dfe179b01577eb6771f27a3297 to your computer and use it in GitHub Desktop.
Typescript Express Server Api Setup

TYPESCRIPT EXPRESS API SETUP

Install Dependencies

yarn add express dotenv cors inversify jsonwebtoken reflect-metadata
yarn add typescript @types/express @types/node ts-node-dev @types/cors concurrently nodemon -D

Generate tsconfig.json file

npx tsc --init

Edit tsconfig.json

- "outDir": "./"
+ "outDir": "./dist"

Configure yours enviroment variables

Generate .env file inside your root project folder and put the next code

PORT=8000

Create your file server

Create index.ts file at your folder root project

import express, { Express, Request, Response } from 'express';
import dotenv from 'dotenv';
import cors from 'cors';

    // Load environment variables from .env file, where API keys and passwords are configured
    dotenv.config();

    // Create Express server
    const app: Express = express();
    
    // Express third party middleware for handling CORS
    app.use(cors());

    // Define port to the Express server will be running on
    const port = process.env.PORT;
    
    // Express test route for checking if everything is working
    app.get('/', (req: Request, res: Response) => {
        res.send('Express + TypeScript Server');
    });

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

Change scripts section in your package.json

{
  "scripts": {
    "build": "npx tsc",
    "start": "node dist/index.js",
    "dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\""
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment