React Nx Tutorial - Step 7: Share Code

Awesome! The application is working end to end! However, there is a problem. Both the backend and the frontend define the Todo interface. The interface is in sync now, but in a real application, over time, it diverges, and, as a result, runtime errors creep in. You should share this interface between the backend and the frontend. In Nx, you do this by creating a library.

Run the following generator to create a library:

npx nx g @nrwl/workspace:lib data

The result should look like this:

myorg/
├── apps/
│   ├── todos/
│   ├── todos-e2e/
│   └── api/
├── libs/
│   └── data/
│       ├── src/
│       │   ├── lib/
│       │   │   └── data.ts
│       │   └── index.ts
│       ├── jest.conf.js
│       ├── tsconfig.app.json
│       ├── tsconfig.json
│       └── tsconfig.spec.json
├── tools/
├── nx.json
├── package.json
└── tsconfig.base.json

Copy the interface into libs/data/src/lib/data.ts.

1export interface Todo {
2  title: string;
3}

A note about VS Code :

If you're using VS Code it may be necessary at this point to restart the TS server so that the new @myorg/data package is recognised. This may need to be done every time a new workspace library is added.

Refactor the API

Now update apps/api/src/app/todos.ts to import the interface:

1import { Express } from 'express';
2import { Todo } from '@myorg/data';
3
4const todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }];
5
6export function addTodoRoutes(app: Express) {
7  app.get('/api/todos', (req, resp) => resp.send(todos));
8  app.post('/api/addTodo', (req, resp) => {
9    const newTodo = {
10      title: `New todo ${Math.floor(Math.random() * 1000)}`,
11    };
12    todos.push(newTodo);
13    resp.send(newTodo);
14  });
15}

Update the React application

Next import the interface in apps/todos/src/app/app.tsx:

1import React, { useEffect, useState } from 'react';
2import { Todo } from '@myorg/data';
3
4export const App = () => {
5  ...
6};
7
8export default App;

Every time you add a new library, you have to restart npx nx serve.

So restart both npx nx serve api and npx nx serve todos and you should see the application running.