How to Fix the "Unexpected Token" Error in JavaScript
Getting an “Unexpected Token” error in JavaScript can be frustrating, especially when your code looks perfectly fine. This error usually means JavaScript has found something it cannot understand, such as a missing bracket, an extra symbol, or HTML where JSON data should be.
One common example is SyntaxError: Unexpected token ‘<‘, which often appears when an application expects a JSON response but receives an HTML page instead.
What Does the Unexpected Token Error Mean?
The Unexpected Token error occurs when JavaScript finds a character, symbol, or piece of code that does not match the expected syntax. In simple words, JavaScript expects something in a particular place but finds something different.
JavaScript uses a parser to read and understand code. When the parser finds an invalid structure, it stops processing the code and reports a SyntaxError.
For example, consider this code:
Incorrect JavaScript:
const username = "Alex"; console.log(username;
The console.log() statement is missing a closing parenthesis. JavaScript cannot understand the complete statement, so it reports a syntax error.
Correct JavaScript:
const username = "Alex"; console.log(username);
How JavaScript Reads and Parses Code
JavaScript uses a parser to check whether your code follows the language’s syntax rules. It examines different elements, including:
- Keywords such as let, const, and function.
- Operators such as +, –, and =.
- Parentheses and curly brackets.
- Strings and variable names.
- Functions and expressions.
If these elements appear in the wrong order or have incorrect formatting, the parser may report an unexpected token error.
Why Does JavaScript Report an Unexpected Token?
JavaScript reports this error when it encounters something it cannot understand in the current context.
Here are some common reasons:
- Missing brackets: Your code has an opening bracket without a matching closing bracket.
- Extra symbols: You have added an unnecessary comma, parenthesis, or curly bracket.
- Incorrect JSON: Your data does not follow valid JSON formatting rules.
- HTML instead of JSON: Your API returns an HTML page when your application expects JSON.
- Invalid syntax: Your JavaScript statement does not follow the correct language structure.
The error message often shows the unexpected character, which gives you a useful starting point for debugging. However, the actual mistake may appear just before the character mentioned in the error.
Common Types of Unexpected Token Errors
The unexpected token error can appear in different forms depending on the problem in your code or the data your application receives. Each error message gives you a clue about what JavaScript cannot understand.
Let’s look at some common types and their examples.
SyntaxError: Unexpected Token '<'
This is one of the most common errors when working with JavaScript and APIs. It usually occurs when your application expects JSON but receives an HTML document instead.
For example:
fetch('/api/users')
.then(response => response.json())
.then(data => console.log(data));If the server returns an HTML error page instead of JSON, the response.json() method cannot read it.
An HTML document often starts with:
<!DOCTYPE html> <html>
When JavaScript tries to parse this HTML as JSON, it encounters the < character and reports:
SyntaxError: Unexpected token '<'
Common reasons include:
- An incorrect API URL.
- A missing API endpoint.
- A server error page.
- A redirect to an HTML login page.
SyntaxError: Unexpected Token '}'
This error often appears when your code contains an extra closing curly bracket or an incorrectly structured object.
Incorrect JavaScript:
const user = { name: "Alex", age: 20 }};
Correct JavaScript:
const user = {
name: "Alex",
age: 20
};
Always check your opening and closing curly brackets when this error appears.
SyntaxError: Unexpected Token ')'
console.log("Hello"));
The extra closing parenthesis causes JavaScript to report a syntax error.
Correct JavaScript:
console.log("Hello");
Check your function calls and make sure every opening parenthesis has a matching closing parenthesis.
SyntaxError: Unexpected Identifier
An unexpected identifier error occurs when JavaScript finds a variable name, function name, or keyword where it expects something else.
Incorrect JavaScript:
const user = {
name: "Alex"
age: 20
};
The object is missing a comma between its properties.
Correct JavaScript:
const user = {
name: "Alex",
age: 20
};
Adding the missing comma fixes the problem.
Tip: Always read the complete error message instead of focusing only on the unexpected character. It can help you understand where JavaScript detected the problem and what you should check first.
This error often appears when your code contains an extra closing curly bracket or an incorrectly structured object.
Incorrect JavaScript:
What Causes the Unexpected Token Error?
Before fixing the unexpected token error, you need to understand why it happens. The problem does not always come from JavaScript syntax. Sometimes your code is incorrect, while other times your application receives data in an unexpected format.
Here are the most common causes.
Invalid JavaScript Syntax
JavaScript follows specific syntax rules. If you forget a comma, add an extra bracket, or write a statement incorrectly, the parser may report an unexpected token error.
Incorrect JavaScript:
let age = 20;
if (age > 18 {
console.log("Adult");
}
The condition is missing a closing parenthesis.
Correct JavaScript:
let age = 20;
if (age > 18) {
console.log("Adult");
}
Always check your brackets, parentheses, quotation marks, and operators when this error appears.
Receiving HTML Instead of JSON
This is a common problem in applications that use APIs.
Suppose your JavaScript application sends a request to an API and expects a JSON response. However, the server returns an HTML page instead.
This can happen when:
- The API endpoint does not exist.
- The server returns a 404 Not Found page.
- The backend service is unavailable.
- The server redirects the request to a login page.
- A reverse proxy returns an HTML error page.
When JavaScript tries to read that HTML as JSON, it may report SyntaxError: Unexpected token ‘<‘.
Missing or Extra Brackets and Parentheses
Brackets help JavaScript understand how your code is organized. Missing or extra brackets can break that structure.
Incorrect JavaScript:
{
"name": "Alex",
"age": 20
}
The array is missing its closing square bracket.
Correct JavaScript:
const products = [
"Laptop",
"Keyboard",
"Mouse"
];
Check that every opening bracket has a matching closing bracket
Incorrect JSON Formatting
JSON (JavaScript Object Notation) uses specific formatting rules to store and exchange data. Unlike regular JavaScript objects, JSON requires double quotes around property names and string values.
Invalid JSON:
{
name: ‘Alex’,
age: 20,
}
This example contains three formatting problems:
- The property names do not use double quotes.
- The string uses single quotes.
- There is a trailing comma.
Valid JSON:
{
"name": "Alex",
"age": 20
}
You can use an online JSON validator to check whether your data follows the correct format before using it in your application
Wrong API Endpoint or Server Response
An incorrect API URL can send your request to the wrong location. Instead of receiving the expected JSON data, your application might receive an HTML page from your website or server.
For example, your application may request:
fetch(‘/api/user’);
But the actual endpoint might be:
/api/users
That small difference can lead to an unexpected response.
Always confirm the endpoint in your API documentation or backend configuration. You should also inspect the response in your browser’s Network tab to see what the server actually returns.
Using Unsupported JavaScript Features
Some JavaScript features do not work in older browsers or outdated runtime environments.
For example, an older JavaScript environment may not support optional chaining:
const city = user?.address?.city;
If the environment cannot understand this syntax, it may report a parsing error.
You can use tools such as Babel to convert modern JavaScript into code that older environments can understand.
How to Fix the Unexpected Token Error
Once you understand the cause, fixing the unexpected token error becomes much easier. The best approach is to check your code, inspect the server response, and correct the problem step by step.
Here are some practical methods you can follow.
Step 1: Check the Browser Console for Errors
Start by opening your browser’s Developer Tools. You can usually press F12 or right-click the page and select Inspect.
Next, open the Console tab and look for the complete error message.
For example:
Uncaught SyntaxError: Unexpected token ‘<‘
at app.js:15
This message tells you that JavaScript detected a problem around line 15 of app.js.
Check the reported line and the code around it. Sometimes the actual mistake appears just before the location shown in the error message.
Step 2: Inspect the Actual API Response
If the error appears after an API request, check what the server actually sends back.
Follow these steps:
- Open your browser’s Developer Tools.
- Select the Network tab.
- Reload your webpage.
- Find and select the API request.
- Open the Response section.
Check whether the response contains valid JSON, an HTML page, an error message, or an empty response.
This helps you identify whether the problem comes from your JavaScript code or the server.
Step 3: Check the Content-Type Header
The Content-Type header tells your application what type of data the server returns.
For JSON responses, the server should normally use:
Content-Type: application/json
You can check this header before parsing the response:
fetch(‘/api/users’)
.then(response => {
const contentType = response.headers.get(‘content-type’);
if (!contentType || !contentType.includes(‘application/json’)) {
throw new Error(‘Expected a JSON response’);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
This example checks the response type before calling response.json().
Remember, a Content-Type header does not guarantee that the response contains valid JSON. The actual response body must also follow JSON formatting rules.
Step 4: Verify HTTP Status Codes
HTTP status codes tell you whether a server request succeeded or failed.
Here are some common status codes:
Status Code | Meaning |
200 | OK |
301 | Moved Permanently |
401 | Unauthorized |
403 | Forbidden |
404 | Not Found |
500 | Internal Server Error |
502 | Bad Gateway |
503 | Service Unavailable |
You can check the response status in JavaScript using the response.ok property:
fetch(‘/api/users’)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
This helps you detect unsuccessful HTTP responses before processing their data
Step 5: Correct JavaScript Syntax
If the error comes from your JavaScript code, review the line mentioned in the console.
Look for missing brackets, extra parentheses, incorrect quotation marks, and missing commas in objects or arrays.
You can also use an editor such as Visual Studio Code to highlight syntax problems while writing code.
Step 6: Validate JSON Data Before Parsing
The JSON.parse() method converts a valid JSON string into a JavaScript value. However, it throws a SyntaxError if the supplied string does not follow JSON rules.
You can use try…catch to handle invalid JSON:
.
const jsonData = '{"name":"Alex","age":20}';
try {
const user = JSON.parse(jsonData);
console.log(user);
} catch (error) {
console.error('Invalid JSON:', error.message);
}
This approach helps your application handle parsing errors without stopping unexpectedly.
Step 7: Check Your API Endpoint and Server
If your JavaScript code looks correct but the error continues, investigate the backend.
Check whether the API endpoint exists, the server is running, and the backend returns JSON instead of an HTML error page.
Also, review authentication settings, server redirects, and backend logs. These checks can help you find problems that are not visible in your frontend code.
How to Fix SyntaxError: Unexpected Token '<' Specifically
The SyntaxError: Unexpected token ‘<‘ error is common in JavaScript applications that use the Fetch API to get data from a server. It usually means your application expects JSON but receives an HTML document instead.
For example, your code may request user information from an API, but the server sends an HTML error page. When JavaScript tries to parse that page as JSON, it encounters the < character and throws an error.
Here are some ways to fix this problem.
Identify Why the Server Returns HTML
First, check the API response in your browser’s Network tab.
If the response starts with <!DOCTYPE html> or <html>, your application is receiving an HTML document instead of JSON.
Check the following:
- Is the API URL correct?
- Does the API endpoint exist?
- Is your backend server working?
- Does the server return the expected JSON data?
- Is your request using the correct HTTP method?
Finding the actual response helps you fix the source of the problem instead of changing JavaScript code unnecessarily.
Check for Login Redirects and Server Error Pages
Some websites redirect users to a login page when their authentication session expires. Other servers return HTML error pages when a request fails.
For example, your application may request data from a protected API endpoint. If the user is not authenticated, the server might return an HTML login page instead of JSON.
Check the request’s status code, redirect behavior, and final response URL in the Network tab. If authentication is the problem, fix the session or authorization settings.
Use Safe JSON Parsing in JavaScript
You can make API requests easier to debug by reading the response as text before parsing it.
Here is a reusable example:
async function safeJsonFetch(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const contentType = response.headers.get('content-type') || '';
if (!contentType.includes('application/json')) {
throw new Error(
`Expected JSON but received: ${contentType || 'unknown content type'}`
);
}
const text = await response.text();
try {
return JSON.parse(text);
} catch (error) {
throw new Error(`Invalid JSON response: ${error.message}`);
}
}
safeJsonFetch('/api/users')
.then(data => console.log(data))
.catch(error => console.error('Request failed:', error));
This function performs three important checks:
- HTTP status: It identifies unsuccessful requests before parsing.
- Content-Type: It checks whether the server claims to return JSON.
- JSON parsing: It checks whether the response body contains valid JSON.
This approach provides clearer error messages and makes debugging easier.
Handle Failed API Requests Properly
A good application should not stop working just because an API request fails.
Use proper error handling to show a helpful message instead of leaving users with a broken page.
For example:
async function getUsers() {
try {
const response = await fetch('/api/users');
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const users = await response.json();
console.log(users);
} catch (error) {
console.error('Unable to load users:', error.message);
}
}
getUsers();
This example handles network errors, unsuccessful HTTP responses, and JSON parsing errors.
You can also display a simple message in your application when a request fails. This helps users understand that the data could not load instead of showing a technical error.
How to Prevent Unexpected Token Errors
Fixing an unexpected token error is important, but preventing it can save you time during future development. A few good coding practices can help you avoid common syntax and JSON parsing problems.
Validate JSON Before Using JSON.parse()
Always make sure your JSON data follows the correct format before parsing it.
If your application receives data from an external API, do not assume that every response contains valid JSON.
Use a JSON validator during development and handle parsing errors with try…catch.
Add Proper Error Handling
Never assume that every API request will succeed. Servers can become unavailable, network connections can fail, and authentication sessions can expire.
Use these JavaScript features to handle problems:
- try…catch for handling errors.
- response.ok for checking HTTP status.
- Content-Type checks for identifying the expected response format.
- Clear error messages for easier debugging.
These practices make your application more reliable and easier to maintain.
Test API Responses During Development
Test your API endpoints before connecting them to your frontend application.
Tools such as Postman and curl can help you send requests and inspect server responses.
Check the response body, HTTP status, headers, and endpoint URL. Testing these details early can help you find problems before they affect your users.
Use a JavaScript Linter
A JavaScript linter checks your code for common mistakes and possible problems.
For example, ESLint can identify syntax issues, suspicious code patterns, and other programming mistakes.
You can also use code editors such as Visual Studio Code to highlight errors and improve your coding workflow.
These tools cannot detect every server-side problem, but they can make debugging much easier.
Conclusion
The Unexpected Token error in JavaScript may look confusing, but finding its cause becomes easier when you know what to check. It can result from invalid syntax, missing brackets, incorrect JSON formatting, or an API that returns HTML instead of JSON.
Start by checking the browser console and inspecting the actual response in the Network tab. Then verify the Content-Type header, HTTP status code, and API endpoint. If the problem comes from invalid syntax or JSON, correct the formatting before running your code again.
Most importantly, don’t assume that every API request will return valid JSON. Add proper error handling and validate responses before parsing them. These simple practices can help you prevent unexpected token errors and build more reliable JavaScript applications.
Frequently Asked Questions
What Does Unexpected Token Mean in JavaScript?
An unexpected token means JavaScript found a character or piece of code that does not match the expected syntax. It can happen because of missing brackets, extra symbols, incorrect formatting, or invalid code.
Why Am I Getting Unexpected Token '<'?
This error usually appears when JavaScript expects JSON but receives HTML. The response may contain a login page, a 404 error page, or another server-generated document. Check the API response in your browser’s Network tab to find the exact cause.
Is Unexpected Token a JavaScript or JSON Error?
It can be either. JavaScript reports syntax errors when it cannot understand code. The same type of error can appear when JSON.parse() or response.json() tries to read invalid JSON data.
How Do I Fix Unexpected Token in JSON?
First, inspect the JSON string and look for missing commas, incorrect quotation marks, extra brackets, or other formatting problems. You can use a JSON validator to identify mistakes. Then correct the data before passing it to JSON.parse().
Can a Wrong API URL Cause an Unexpected Token Error?
Yes. An incorrect API URL may return an HTML 404 page instead of the JSON data your application expects. Check the endpoint, HTTP status, and response body to confirm whether the URL is correct.