Luciano Serruya Aloisi

TypeScript: sharing type definitions seamlessly between server and client (with React.js)

This note will not be a fully detailed tutorial, as it would repeat many things already explained in the original version. In this note I will explain briefly how to set up your React app (created with create-react-app) to share types between client and server.

You can find the repo for this demo app here


  1. Create your app with create-react-app
npx create-react-app <PROJECT_NAME> --typescript
  1. Add the exact same server directory inside src than in the Vue.js version. The tsconfig.json file won't be the exact same though, add the following content
// src/server/tsconfig.json

{
  "include": ["*.ts"],
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "dist",
    "esModuleInterop": true
  }
}
  1. Having created our React app with CRA, is not that easy to customize the webpack configuration used under the hood (props to Vue.js on that, it is really easy to do so). We will need a third-party dependency to customize webpack's development server configuration. In this note, we will be using react-app-rewired. Install it with npm install --save-dev react-app-rewired and follow the instructions available on their README file.

  2. Once installed, create a file named config-overrides.js right next to your node_modules directory and add the following content inside it

const { configureServer } = require("./src/server/dist");

module.exports = {
  webpack: function (config, env) {
    return config;
  },
  jest: function (config) {
    return config;
  },
  devServer: function (configFunction) {
    return function (proxy, allowedHost) {
      const config = configFunction(proxy, allowedHost);
      config.before = configureServer;
      return config;
    };
  },
  paths: function (paths, env) {
    return paths;
  }
};

We are doing the same as in the original note, importing our configureServer function and passing it to the before property for webpack's development server configuration

  1. Install nodemon (npm install --save-dev nodemon) and create a file named nodemon.json right next to your node_modules directory. Add the following content inside it
{
  "watch": ["src/server"],
  "exec": "tsc -p src/server && npm start",
  "ext": "ts"
}
  1. Add a new npm-script to run nodemon
"scripts": {
  "dev": "nodemon",
  ...
},

And we are done! You can now share type definitions between your node.js backend and your React app seamlessly.

Hope you liked it!

🐦 @LucianoSerruya

📧 lucianoserruya (at) gmail (dot) com