DEV Community

Cover image for Fast setup of a TypeScript React project
Liam Cassidy
Liam Cassidy

Posted on

Fast setup of a TypeScript React project

There are two purposes of this tutorial. The first is to quickly get you up and running with a TypeScript and React project. Second, to set up a mocked backend so that you can immediately iterate on an idea.

Spin up typescript project with CRA (create react app)

npx create-react-app my-app --template typescript
Enter fullscreen mode Exit fullscreen mode

Add mock-backend for fast iteration without backend setup

One thing that always slows me down when iterating on a prototype is setting up a back-end to seed data in the front-end in a realistic fashion. Now, you could do this by returning mock data from your fetches; however, this doesn't allow you to fully test the integration between the front-end and the backend. Instead we can use a server mock at the network layer.

In this case we'll use msw. You can read more about msw in the following documentation, but if you're looking to speed through this tutorial, just think of it as a more sophisticated way of mocking a server that avoids mocking within your application.

npm install msw --save-dev

# copies `mockServiceWorker.js` to your public directory
node_modules/.bin/msw init public
Enter fullscreen mode Exit fullscreen mode

sources:

create your handlers file:

// src/mocks/handlers.js
import { rest } from 'msw'

// add handlers:

export const handlers = [
  rest.post('/login', (req, res, ctx) => {
    // Persist user's authentication in the session
    sessionStorage.setItem('is-authenticated', true)
    return res(
      // Respond with a 200 status code
      ctx.status(200),
    )
  }),
  rest.get('/user', (req, res, ctx) => {
    // Check if the user is authenticated in this session
    const isAuthenticated = sessionStorage.getItem('is-authenticated')
    if (!isAuthenticated) {
      // If not authenticated, respond with a 403 error
      return res(
        ctx.status(403),
        ctx.json({
          errorMessage: 'Not authorized',
        }),
      )
    }
    // If authenticated, return a mocked user details
    return res(
      ctx.status(200),
      ctx.json({
        username: 'admin',
      }),
    )
  }),
]
Enter fullscreen mode Exit fullscreen mode

create a server.js file in the same directory:

// src/mocks/server.js
import { setupWorker } from 'msw';
import { handlers } from './handlers';

const worker = setupWorker(...handlers);
worker.start();
Enter fullscreen mode Exit fullscreen mode

now we need to start the mock server in the browser when our app loads:

so add this line below your imports in your App.tsx file:

import React from 'react';
import './App.css';

/**
 * Please prefer conditionally including a mocking file via bundler
 * during the build of your application.
 */
if (process.env.NODE_ENV === 'development') {
  require('./mocks/server');
}
Enter fullscreen mode Exit fullscreen mode

now, if you open your console in the browser you should see the following output:

[MSW] Mocking enabled.
Enter fullscreen mode Exit fullscreen mode

Now you can begin to add endpoints in the handlers.js file to mimic the behavior of your backend before it's actually built. I've found that this approach can allow you to keep momentum when starting a project and suss out requirements for your backend in the process.

I hope you found this article helpful. Please feel free to add suggestions, questions, and request follow up articles!

Best,

Liam

I'll follow up on questions as fast as I can, but for professional assistance, feel free reach out on fiverr:
https://www.fiverr.com/liamcassidy298

Top comments (0)