Full-stack Web Technologies

CHAPTER 2
Scaffolding the Server

  1. Create a file src/server.ts:

    import express from "express";
    import cors from "cors";
    import morgan from "morgan";
    
    const app = express();
    
    app.use(cors());
    app.use(morgan("dev"));
    app.use(express.json());
    
    app.get("/", async (req, res) => {
      res.json({ message: "hello!" });
    });
    
    const { PORT } = process.env;
    app.listen(PORT, () => {
      console.log(`Forum API listening on port ${PORT}`);
    });
    
  2. Select it as the "main" file in package.json:

    {
      // ...
      "main": "src/server.ts"
      // ...
    }
    
  3. Add the PORT variable to the .env file. (We will assume 8888 here.)

  4. Run the server with

    bun run src/server.ts
    

    and check that it works.

  5. Change to another terminal (install httpie if you don't have it), and run:

    http GET localhost:8888/
    

    You should get something like:

    HTTP/1.1 200 OK
    Access-Control-Allow-Origin: *
    Content-Length: 20
    Content-Type: application/json; charset=utf-8
    Date: Wed, 24 Apr 2024 17:51:01 GMT
    ETag: W/"14-li7HDh+tAWW33cIYjDrXLcX526M"
    X-Powered-By: Express
    
    {
        "message": "hello!"
    }
    
  6. Create "scripts" in package.json to launch the server in development and production:

    {
      "scripts": {
        "dev": "bun --hot src/server.ts",
        "start": "NODE_ENV=production bun src/server.ts"
      }
    }
    
  7. Start the server with bun run dev and check that if you change server.ts the server reloads.