πŸ”§ Error Fixes
Β· 1 min read

JavaScript SyntaxError: Unexpected Token β€” How to Fix It


SyntaxError: Unexpected token '<'

The JavaScript parser hit something it didn’t expect.

Why this happens

The JavaScript engine expects valid JS syntax but received something else β€” often an HTML page (starting with <) returned instead of a JS file. This happens when a script URL 404s and the server returns an HTML error page, or when you try to parse a non-JSON response as JSON.

Fix 1: HTML in a JS file

SyntaxError: Unexpected token '<'

You’re loading an HTML page instead of a JS file. Check your script src:

<!-- ❌ Wrong path β€” server returns HTML 404 page -->
<script src="/scrpts/app.js"></script>

<!-- βœ… Correct path -->
<script src="/scripts/app.js"></script>

Fix 2: JSON parse error

// ❌ Response is HTML, not JSON
const data = JSON.parse('<html>...');

// βœ… Check the response first
const res = await fetch('/api/data');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();

Fix 3: Missing comma or bracket

// ❌ Missing comma
const obj = { a: 1 b: 2 };

// βœ…
const obj = { a: 1, b: 2 };

Alternative solutions

Check your bundler output β€” if using Webpack or Vite, ensure the publicPath or base config matches your deployment URL so assets resolve correctly.

Use your browser’s Network tab to inspect what the script URL actually returns. If it’s HTML, the path is wrong or the server isn’t configured to serve static files.

Prevention

  • Use a linter (ESLint) and formatter (Prettier) to catch syntax errors before they reach the browser.
  • Always check response.ok before calling .json() on fetch responses.

Related: Cannot Read Properties of Null fix Β· Unexpected Token in JSON fix