🎓 A1Learner
🔍
0 of 50 lessons completed

The API Base URL

The API base URL is the shared start of every API address in the app. It holds the server address in one place.

One constant for the server address

const API_URL = 'http://localhost:3001';

Joining the base URL with a path

fetch(API_URL + '/notes')

The same base URL for a POST

fetch(API_URL + '/notes', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
});

Example

import { useState } from 'react';

const API_URL = 'http://localhost:3001';

export default function App() {
  const [url] = useState(API_URL + '/notes');

  return (
    <div>
      <h1>Notes</h1>
      <p>{url}</p>
    </div>
  );
}

Key points

  • A base URL is a constant, such as 'http://localhost:3001'.
  • Every fetch joins the base URL with a path, such as '/notes'.
  • One constant means one place to change when the server moves.
  • The constant sits at the top of the file, above the component.

In this example, the constant holds the server address, and the component joins it with '/notes'. The first render shows the full address on the page. In the real app, the fetch call uses the same joined address to ask the API for the notes.

Note

The base URL carries no path at the end, so each fetch adds its own path.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does the app keep the API address in one constant?