JavaScript SyntaxError: Unexpected token — Parser found invalid syntax
SyntaxError: Unexpected token in JavaScript
Verified against MDN Web Docs — SyntaxError, ECMAScript 2022 spec §16.1.7, JSON specification RFC 8259 · Updated June 2026
> quick_fix
For JSON.parse() errors, validate the string is valid JSON (try jsonlint.com or JSON.stringify then parse it back). For source code errors, check the line number in the stack trace for mismatched brackets, missing commas, or unsupported syntax.
// JSON parse — wrap in try-catch and validate
try {
const data = JSON.parse(jsonString);
} catch (e) {
if (e instanceof SyntaxError) {
console.error('Invalid JSON:', e.message);
console.error('Input was:', jsonString.slice(0, 200));
}
}
// Safe JSON parse utility
function safeJsonParse(str, fallback = null) {
try {
return JSON.parse(str);
} catch {
return fallback;
}
}
// Check for HTML in JSON response (server returned error page)
if (typeof jsonString === 'string' && jsonString.startsWith('<')) {
throw new Error('Server returned HTML instead of JSON — check the API endpoint and response status');
}What causes this error
SyntaxError: Unexpected token is thrown by the JavaScript parser when it encounters a character or token it does not expect at that position. Two distinct scenarios: (1) Source code syntax error — the JS file itself has invalid syntax (mismatched braces, missing comma in object literal, arrow function syntax in an ES5-only environment). (2) Runtime JSON.parse() error — you call JSON.parse() on a string that is not valid JSON (HTML error page, plain text, malformed JSON with trailing comma).
How to fix it
- 01
step 1
Check if this is a source code error or a JSON.parse error
If the error points to a line in your .js/.ts source file, it is a syntax error in code. If the stack trace shows `JSON.parse`, you are trying to parse a non-JSON string. The fix approach differs for each.
- 02
step 2
For JSON.parse errors: inspect the raw response
Log the string before parsing: `console.log('Parsing:', str.slice(0, 500))`. If it starts with `<!DOCTYPE` or `<html`, the server returned an HTML error page instead of JSON. Check the HTTP status code — a 404 or 500 often returns HTML.
- 03
step 3
For source code SyntaxError: check the line number
The stack trace includes a line and column number. Go to that exact line. Common issues: missing comma in object literal `{a: 1 b: 2}`, mismatched bracket/parenthesis, trailing comma in function arguments (forbidden in ES3/ES5), or an arrow function in code transpiled without Babel.
- 04
step 4
Check your Babel/transpiler configuration for ES6+ features
If your code uses modern syntax (arrow functions, destructuring, optional chaining) but runs in an environment without transpilation (old Node.js version, legacy browser), the parser will throw SyntaxError. Update your Babel config, target, or Node.js version.
- 05
step 5
Validate JSON strings before parsing
Use a utility that handles the try-catch for you. For API responses, always check `response.ok` before calling `response.json()` — a failed fetch (4xx/5xx) often returns HTML. Check: `if (!response.ok) throw new Error(response.statusText);` before `await response.json()`.
How to verify the fix
- The exact string that caused JSON.parse to fail should now be validated or the source of the bad JSON fixed
- For source code syntax errors: the script should load and execute without errors
- Test in the target browser/Node.js version to confirm syntax is supported
Why SyntaxError: Unexpected token happens at the runtime level
JavaScript parsing is a two-phase process: lexing (tokenizing the source text into tokens) and parsing (building the AST from tokens). SyntaxError is thrown during the parse phase when the parser encounters a token sequence that violates the grammar rules. For JSON.parse(), V8 and other engines implement a strict JSON grammar parser (a subset of JavaScript) — JavaScript comments, trailing commas, single quotes, and undefined values are all illegal in JSON despite being legal in JavaScript object literals.
Common debug mistakes for SyntaxError: Unexpected token
- Calling JSON.parse() on an API response without checking if it is valid JSON first (e.g., when the server returns a 401 HTML login page)
- Writing a JavaScript object literal with a trailing comma and running it in an ES3/ES5-strict environment
- Embedding template literals or backtick strings in code that Babel is not configured to transpile for older targets
- Pasting JSON with JavaScript-style comments (`// comment`) into JSON.parse() — comments are not valid JSON
When SyntaxError: Unexpected token signals a deeper problem
The JSON.parse SyntaxError variant is a boundary problem: the application assumes the server always returns valid JSON but does not defensively handle the case where the server returns HTML (error pages, login redirects, gateway responses). The fix is a fetch wrapper that validates the Content-Type header and response.ok before attempting JSON parsing. For source code SyntaxErrors in production, they indicate a build/transpilation misconfiguration — the code was never tested in the target environment.
Editor's take
SyntaxError: Unexpected token means the JavaScript parser encountered a character or keyword where it doesn't belong according to the language grammar. Unlike runtime errors, this fails at parse time — your code never executes. The challenge is that the error points to where the parser got confused, not where the actual mistake is. A missing closing brace on line 10 might report an unexpected token on line 50 where the parser finally realizes the structure is wrong. The most common production causes: trailing commas in JSON (valid in JS objects since ES5, invalid in JSON), optional chaining `?.` in a Node.js version that doesn't support it, using `import` statements in a CommonJS file without proper bundler configuration, and copy-pasting code that contains invisible Unicode characters (zero-width spaces, non-breaking spaces) that look identical to regular spaces but aren't. In webpack/Vite build pipelines, this error often means a dependency ships untranspiled ES2020+ syntax and your build doesn't process `node_modules`. The fix is adding the package to your transpilation include list. For JSON specifically, use `JSON.parse()` in a try-catch and inspect the error's `position` property — it gives you the exact character offset. Experienced JavaScript developers learn to read SyntaxErrors backwards: find the reported position, then scan upward for the unclosed bracket, missing comma, or mismatched quote that caused the cascade.
By Bikram Nath · Curator · Updated June 2026
Frequently asked questions
Why does JSON.parse throw 'Unexpected token < in JSON at position 0'?
This means the string being parsed starts with '<', which is an HTML tag. The server returned an HTML page (usually a 404 error page, authentication redirect, or server error) instead of a JSON response. Fix: check the HTTP status code before parsing, and ensure your API endpoint URL is correct.
Is SyntaxError catchable in JavaScript?
SyntaxErrors in source code are not catchable — they prevent the script from being parsed and executing at all. SyntaxErrors thrown at runtime (from JSON.parse, eval(), or Function constructor) are catchable with try-catch because they occur during execution of already-parsed code.
What is the difference between SyntaxError and TypeError in JavaScript?
SyntaxError means the code (or a string being parsed) does not conform to valid JavaScript/JSON grammar — the parser cannot understand the structure. TypeError means the code is syntactically valid but an operation was performed on a value of the wrong type (e.g., calling a non-function, accessing property of null).