Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

What's the proper way to setup API references during development, when you run the dev API locally?

Writer Sophia Terry

BACKGROUND

I'm setting up a new front-end web projects. The application I'm working on is also a new Visual Studio ASP.Net Core Web API. All of my UI work is part of the same git repository, but is not included in the Web API solution.

For development, I run the API in Visual Studio so that I can easily start/stop and break on code, and I use npm to start and run my UI application from VS Code.

QUESTION

Obviously, I need to make API calls within my application. To do this, I can make calls like:

fetch(')

The obvious problem is that is a local address and this will need to obviously be published to servers for dev and staging as well as production. Instead, I should define some type of environment variable that will replace the hardcoded address with the correct root address, and my code should reference that configuration value

Eventually we are going to setup a CI pipeline for this project, so I need to be sure I'm setting up the types of config settings that will differ from server to server the application is published too. That said, my google searches aren't helping me find the proper way to define web API addresses in environment variables or configuration files that I can access within my code.

How do I setup an npm/React application so that it can access a config-define API address, that can later be easily changed based off of the environment it's published too?

6

1 Answer

Create a config.js in the src... In there do something like this:

export const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || '

And then wherever you need it you can import and use it like so:

import { API_BASE_URL } from './config';

Something like:

 fetch(`${API_BASE_URL}/auth/etc...`)

EDIT:

Try this:

import React from 'react';
function App() { return <div>{process.env.NODE_ENV}</div>; // (if in developement should say development)
}
export default App;

Let me know if it says development

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.