Building a universal web app with React

Let’s build a universal/isomorphic web application with React.

remarkablemark
2 min readOct 31, 2016

Prerequisite

Express

In order for the component logic to work on the client-side, we’ll need to build and load a client script in the browser.

But first, we’ll need to configure our Express server to serve static files (line 11):

server.js

The public/ directory will contain all the static assets. Let’s create a simple stylesheet since we’re here:

public/style.css

Now let’s update our main component to full HTML markup and load the stylesheet:

Component.jsx

Restart the server and you should see your changes:

$ node server.js$ open http://localhost:3000

Webpack

Now that our static middleware is working, let’s generate our client-side JavaScript bundle. In our case, we’ll use webpack as our module bundler.

Let’s install webpack globally:

$ npm install webpack@1 -g

If you don’t want to install webpack globally, you can also install it locally by not passing the -g flag.

But in order to run webpack on the CLI, you’ll need to use the binary:

$ ./node_modules/webpack

Alternatively, you can create an npm script for webpack.

Install babel-core and babel-loader, which will be used by webpack to compile JSX to JS:

$ npm install babel-core babel-loader

Note:babel-preset-react will also used by webpack, but we’ve already installed it previously.

We can now create our webpack configuration:

webpack.config.js

Also, we’ll need to create our entry file (for webpack):

client.js

Finally, let’s load the build script in our main component (line 20):

Component.jsx

Build the bundle and restart the server:

$ webpack && node server.js$ open http://localhost:3000

Open the application or refresh it if it’s already open. If you click on the button, the alert will pop up. Success!

So what’s next? If you want to pass props from the server, it’ll be a little tricky given our universal setup. In the next tutorial, I’ll cover just that. Feel free to check out the code for this tutorial as well as other videos in my React playlist.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (5)

Write a response