Express Integration

We have written all our logic in our controllers, and middlewares. Now we will finally write some actual express code, and bring all the different contracts, controllers, and middlewares together to initialize actual express endpoints using the ts-rest/express integration package.

Initializing the app

We first need to initialize an express app, and set up the cors, and the bodyParser middlewares.

import bodyParser from 'body-parser';
import cors from 'cors';
import express from 'express';
 
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Making the express endpoints

We can instantiate the express endpoints from the ts-rest contracts, and controllers that we wrote earlier using the createExpressEndpoints function from ts-rest/express.

import { createExpressEndpoints } from '@ts-rest/express';
 
createExpressEndpoints(UserContract, UserRouter, app);
createExpressEndpoints(PostContract, PostRouter, app, {
  globalMiddleware :[ Auth ], /* Our authentication middleware from earlier*/
});

Just like that we have have successfully integrated our code as express endpoints. The thing to appreciate is that we could have also used some other web framework with minimal changes.

One thing to notice is that in the Posts endpoints, we have a globalMiddleware array. We can pass multiple middlewares here, and they will be applied to each endpoint. Currently we only needed to authenticate each endpoint, hence we have passed only the Auth middleware function.

Running the server

Go ahead and run your server on the port of your choosing.

const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Now you may use any tools of your choice to test this server such as postman but we are gonna do something way cooler to test it.