As a frontend application becomes more mature, it often develops a need to talk to multiple backend services. Each one of those backends will likely have specific authentication, API routes and configuration which needs to be managed somewhere. One common approach for this is a backend-for-frontend pattern where a dedicated backend manages all of this for your frontend. However, if you do not have the luxury of spawning a backend just for your webapp, there are some nice options for making the setup less painfull with webpack.
webpack.DefinePlugin
This plugin will override env variables used in code with variables defined in an .env
file.
new webpack.DefinePlugin({
'process.env': {
API_HOST_USERS: JSON.stringify(process.env.API_HOST_USERS),
API_HOST_BOOKINGS: JSON.stringify(
process.env.API_HOST_BOOKINGS
),
API_HOST_PARTNER: JSON.stringify(process.env.API_HOST_PARTNER),
},
}),
webpack dev server
The webpack dev server will provide config during development. This config will not be used in a production build.
const config = {
...
devServer: {
hot: true,
port: 3000,
inline: true,
stats: 'errors-only',
host: '0.0.0.0',
proxy: {
'/users-api': {
target: process.env.API_HOST_USERS,
changeOrigin: true,
},
'/bookings-api': {
target: process.env.API_HOST_BOOKINGS,
changeOrigin: true,
},
'/partner-api': {
target: process.env.API_HOST_PARTNER,
changeOrigin: true,
},
},
},
};
Top comments (0)