Fix: 'Unexpected token < in JSON at position 0' Error: A Complete Troubleshooting Guide

If you are working with JavaScript and APIs, encountering the 'Unexpected token < in JSON at position 0' error is a common rite of passage. This error typically occurs when your code expects a JSON object but receives a string starting with a '<' character instead—which is almost always the start of an HTML tag like <!DOCTYPE html> or <html>.

This guide will walk you through the steps to identify why your app is receiving HTML instead of JSON and how to fix it effectively.

Step 1: Inspect the Network Response

The first step in troubleshooting is seeing exactly what the server is sending back. You can do this using your browser's Developer Tools.

  • Open your website and press F12 (or Right-Click > Inspect).
  • Go to the Network tab.
  • Trigger the action that causes the error (e.g., clicking a button or refreshing the page).
  • Find the specific API request in the list and click on it.
  • Check the Response or Preview tab. If you see HTML code (like a 404 page or a login screen), you have found the source of the problem.

Step 2: Verify the API URL

The most frequent cause of this error is a wrong URL path. If you attempt to fetch() data from an incorrect path, the server might return a 404 Error page in HTML format. When your JavaScript tries to run response.json() on that HTML, it fails at the very first character (the < symbol).

Ensure that your fetch URL is absolute (e.g., https://api.example.com/data) or that your relative path (e.g., /api/data) is correct relative to your domain.

Step 3: Check Server-Side Errors

If the URL is correct, the server might be crashing and sending back a 500 Internal Server Error page. Many web servers (like Apache or Nginx) are configured to send a standard HTML error page when a script fails.

Check your server logs (Node.js, PHP, or Python logs) to see if there is a crash occurring before the JSON response is sent. Ensure your server-side code is explicitly setting the header: Content-Type: application/json.

Step 4: Handle Non-JSON Responses in Code

To prevent your application from crashing when this happens, you should always validate the response before attempting to parse it as JSON. Use the response.ok property and check the status code.

Correct Implementation Example:

fetch('/api/data')    .then(response => {      if (!response.ok) {        throw new Error('Network response was not ok');      }      const contentType = response.headers.get('content-type');      if (!contentType || !contentType.includes('application/json')) {        throw new TypeError("Oops, we didn't get JSON!");      }      return response.json();    })    .then(data => console.log(data))    .catch(error => console.error('Fetch error:', error));

Step 5: Check for Authentication Redirects

If your API route is protected, the server might be redirecting your request to a Login Page. Because login pages are HTML, the fetch() request follows the redirect and receives the HTML of the login screen instead of the data you wanted. Ensure your request includes the necessary Authorization headers or cookies to pass the server's security checks.

Summary

The 'Unexpected token <' error is a symptom of your JavaScript trying to read HTML as data. By inspecting the Network tab and validating your API paths, you can quickly identify the source and ensure your application handles errors gracefully without breaking the UI.


💡 Pro Tip: Keep your software updated to avoid these issues in the future.


Category: #Website