1

React ^0.14.0

Node ^5.0.0

Express ^4.0.0

I'm developing a React application and I can no longer hard code the host and port for my client.

Cause now I'll be switching between deploying the server in the the cloud or running it locally - so I need to create a way for the client application to determine it's dynamic host and port in order to make http requests to the correct endpoints of the server(locally or on the web).

Since all the requests are to the "same origin" as the server I figure there are 2 ways to set this up.

1) (Easy way)Client-side: Grab the "location" as soon as the client is initializing, or before each request.

2) Server-side: Use the server's config to determine the host and port and send them as a part of the initial state during server-side rendering.

The first way would definitely be the easiest way to hack up something that works but I feel like if I had more experience deploying servers and switching between different environments I'd find a more sound way with the second method.

I figure experienced teams know common conventions for pulling this off, but without many production level examples online - I be like ¯\_(ツ)_/¯

Nick Pineda
  • 6,354
  • 11
  • 46
  • 66

1 Answers1

2

Server-side:

Using webpack, and especially webpack define plugin, you can inject the right host & port when bundling your application. the right & host come from passing environment dependent variables. And choosing one or another depends on script arguments (production for example).It work for me. Here is my stack:

I create a config file with different port & host depending on my needs (production, cloud, local, ...). I import it using rc. When imported in my webpack config, I had a node in the webpack config:

....
plugins: [
  new dwebpack.DefinePlugin({
    __LOCATION__: production ? rcConfig.location1 : rcConfig.location2
  })
],
....  

Then I can write __LOCATION__ in my javascript code:

<a href={__LOCATION__+"/api/todo"}>see todo</a>

it will be replaced by its value when webpacking

Hope this help :)

Community
  • 1
  • 1
Damien Leroux
  • 11,177
  • 7
  • 43
  • 57