Course contentsShow
← JavaScript
Lesson 2276 of 2,72347. Networking PrimitivesFree lesson

Response.ok and Status Checking

Use the ok boolean and status code to distinguish successful responses from client or server errors.

Response.ok and Status Checking

You'll learn how to reliably detect successful HTTP responses versus client and server errors using Response.ok and status codes.

Why Status Matters

When you make a fetch() request, the promise doesn't automatically reject for HTTP error statuses like 404 or 500. A response that says "not found" is still a valid HTTP response! You need to explicitly check whether the server indicates success.

The ok Boolean

The Response.ok property is your first line of defense. It's true when the status code is in the 200–299 range (success), and false otherwise:

const response = await fetch('https://api.example.com/data');

if (response.ok) {
  const data = await response.json();
  console.log('Success!', data);
} else {
  console.error('Request failed with status:', response.status);
}

Status Codes for Granular Control

For more precise handling, check response.status directly. This gives you the numeric HTTP status code:

const response = await fetch('https://api.example.com/resource');

if (response.status === 404) {
  console.log('Resource not found');
} else if (response.status >= 500) {
  console.log('Server error occurred');
} else if (response.ok) {
  // Handle success
  const data = await response.json();
}

Think of It Like a Traffic Light

response.ok is like seeing a green light—go ahead and process the data. If it's red (false), you need to check response.status to understand why: was the client request bad (400s) or did the server struggle (500s)?

Key Takeaway: Always check response.ok before reading the response body; use response.status when you need to handle specific HTTP error codes differently.