Skip to main content

Command Palette

Search for a command to run...

Understanding the Basic Syntax of fetch() in JavaScript

Updated
3 min read
Understanding the Basic Syntax of fetch() in JavaScript
S

I'm Shubham (@shubhamsinghbundela), I'm a Software Engineer, a Full-stack developer, a tech enthusiast, and a technical writer here on @Hashnode. I have a strong zeal to share my acquired knowledge and I am also willing to learn from others.

When working with APIs in JavaScript, fetch() is one of the most commonly used Web APIs to make HTTP requests.

Let’s break it down step by step 👇

1️⃣ Basic Syntax of fetch()

fetch(url, options);
ParameterTypeRequiredDescription
urlstring✅ YesAPI / endpoint URL
optionsobject❌ NoRequest configuration

2️⃣ Simplest Syntax (GET Request)

fetch("https://api.example.com/data");

Default Behavior

When you call fetch() like this, it automatically uses:

  • Method → GET

  • No request body

  • No custom headers

This is perfect for simply retrieving data.

3️⃣ Syntax with .then()

Since fetch() returns a Promise, we handle the response using .then().

fetch(url, options)
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

4️⃣ Syntax with async/await

A cleaner and more readable way 👇

const response = await fetch(url, options);
const data = await response.json();

Used inside an async function:

async function getData() {
  const response = await fetch(url);
  const data = await response.json();
  console.log(data);
}

5️⃣ Full Options Syntax

When you want full control over the request:

fetch(url, {
  method: "POST",          // HTTP method
  headers: {               // Request headers
    "Content-Type": "application/json",
  },
  body: JSON.stringify({   // Request body
    key: "value",
  }),
  mode: "cors",            // CORS mode
  credentials: "include",  // Cookies handling
  cache: "no-cache",       // Cache control
  redirect: "follow",      // Redirect handling
  signal: controller.signal // Abort request
});

Q: When Do We Use the options Object in fetch()?


Whenever we want to customize the request beyond the default GET call.

1️⃣ When Sending Data to Server (POST / PUT / PATCH)

GET requests don’t send a body, but POST/PUT do — so options are required.

fetch("/api/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "Shubham",
  }),
});

2️⃣ When Sending Custom Headers

Example: Authorization token

fetch("/secure", {
  headers: {
    Authorization: "Bearer token",
  },
});

Q: Why Do We Send Body as JSON.stringify()?

Because HTTP request bodies support only:

  • Text

  • Binary data

They do NOT understand JavaScript objects directly.

So we convert:

👉 JavaScript Object → JSON String

JSON.stringify();

🧠 Think of It Like Language Translation

  • JavaScript Object → Browser language

  • JSON String → Internet / Server language

1️⃣ What Happens If You DON’T Stringify?

fetch("/api", {
  method: "POST",
  body: { name: "Shubham" }, // ❌ Wrong
});

Browser converts object into a string like:

[object Object]

Server receives garbage data ❌

2️⃣ Correct Way

fetch("/api", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "Shubham",
  }),
});

Now request body becomes:

{"name":"Shubham"}

Server understands it ✅

3️⃣ Why JSON Specifically?

Because JSON is:

  • Text-based

  • Language independent

  • Lightweight

  • Easy to parse

Every backend understands JSON:

  • Node.js → JSON.parse()

  • Python → json.loads()

✅ Final Thoughts

fetch() is simple at the surface but powerful when you use the options object.

More from this blog

Shubham Tech. Blog's

55 posts

Problem Solver | Currently Working As a Full Stack Developer, Community Leader At @Dev_Matrix | Previously Contributor at @RealDevSquad, @TeamShiksha