Last updated: Mar 2, 2024
Reading time·6 min
Note: if you got the error "SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON", click on the second subheading.
The "Uncaught SyntaxError: Unexpected token" exception occurs for multiple reasons:
<script />
tag that points to an HTML file instead of a JS file.fetch()
method with an incorrect URL and trying to parse an
HTML response as JSON.<script />
tag that points to an incorrect path.script
tag.You might also see this error as "Uncaught SyntaxError: expected expression, got '<'".
Here is an example of how the error occurs when our script
tag points to an
HTML file instead of a JS file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ Uncaught SyntaxError: Unexpected token '<' ⛔️ --> <!-- ⛔️ Uncaught SyntaxError: expected expression, got '<' ⛔️ --> <script src="index.html"></script> </body> </html>
Make sure that your script
tags point to the correct paths and try renaming
all your files to lowercase letters only.
Sometimes the error is caused if the file name contains uppercase letters or special characters.
Another common cause of the error is forgetting to close a script
tag.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <!-- 👇️ Forgot to close the script tag --> <script console.log("Uncaught SyntaxError: Unexpected token '<'"); </script> </head> <body></body> </html>
The <script
line should be <script>
in the example.
The error also occurs if you have a missing or extra bracket, parenthesis or comma.
// ⛔️ SyntaxError: Unexpected token '}' function sum(a, b) { return a + b; }}
Make sure you don't have any missing or extra square brackets in your arrays.
// ⛔️ Uncaught SyntaxError: Unexpected token ']' const arr = [1, 2, 3]] // 👈️ extra square bracket // ✅ Fixed const arr = [1, 2, 3]
Make sure you don't have a missing comma between the key-value pairs in your objects and the elements in your arrays.
const obj = { 'name': 'bobby' // 👈️ missing comma age: 30 } const obj = { 'name': 'bobby', // ✅ Fixed age: 30 } // ----------------------------------------- const arr = ['a', 'b' 'c'] // 👈️ missing comma const arr = ['a', 'b', 'c'] // ✅ Fixed
Make sure you have closed all of your string literals.
const str = "bobbyhadz.com // 👈️ missing double quote const str = "bobbyhadz.com" // ✅ Fixed
index.js:4
. This means that the error occurred in the index.js
file on line 4
.These syntax errors are very tricky to find, but a general rule of thumb is:
<
),
you are probably trying to read some HTML code that starts with <
.SyntaxError
where you have an extra or a missing
character in your code.Here's another example.
// ⛔️ Uncaught SyntaxError: Unexpected token ':' const obj = { name:: "Tom", } // ✅ Fixed const obj = { name: "Tom", }
We separated the key and value in the object with 2 colons instead of 1, which caused the error.
This could also occur if you have an extra comma.
// ⛔️ Uncaught SyntaxError: Unexpected token ',' const obj = { name: 'Tom',, } // ✅ Fixed const obj = { name: 'Tom', }
However, the brackets and parentheses are the most difficult SyntaxErrors to track down.
You can paste your code into an online Syntax Validator . The validator should be able to tell you on which line the error occurred.The "SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON" error is also caused if you make an HTTP request to a server, get back an HTML response and try to parse the response as JSON.
To resolve this, console.log
the response you're getting from your server
and make sure it's a valid JSON string that doesn't contain any HTML tags.
Network
tab and inspect the response.If your server sends back the correct data, make sure it's Content-Type
response header is set to application/json
and not text/html
.
When JSON data is sent over the network, the Content-Type
header should be set
to application/json
.
If you are making an HTTP request, you can also try to set the Accept
header
to application/json
to indicate to your server that you expect a JSON
response.
const response = await fetch('https://randomuser.me/api/', { method: 'GET', headers: { // set Accept header to application/json Accept: 'application/json', }, });
The Accept HTTP header indicates to the server which content types the client (browser) is able to understand.
Here is a complete example that uses the fetch()
method to fetch data from a
remote API.
async function getUser() { try { const response = await fetch('https://randomuser.me/api/', { method: 'GET', headers: { Accept: 'application/json', }, }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } } getUser().then(data => { console.log(data); });
Your error will most likely be caused when the response.json()
method tries to
parse the HTML that the server responded with as JSON.
In this case, the catch()
method will run and will console.log()
the error.
If you got the error when using JSON.parse, track down where the variable got assigned an HTML string instead of a JSON string.
You can use a try/catch
statement to handle the parsing error if necessary.
try { const parsed = JSON.parse(data); } catch (err) { console.log('An error occurred: ', err); console.log('Data is not a valid JSON string: ', data); }
If you are making an HTTP request to your server, make sure the URL to which you're making a request is correct.
The error occurs when you specify an incorrect URL, e.g. when calling fetch()
.
The URL you are making a request to is sending back an HTML response
(Content-Type
header is set to text/html
) whereas you're probably expecting
to get back a JSON response (Content-Type
header should be
application/json
).
Make sure to specify the correct and complete URL, including the protocol and the path.
Here are some examples.
http://localhost:3000/books http://localhost:3000/books/10 https://bobbyhadz.com/blog/javascript-uncaught-syntaxerror-unexpected-token
If you pass an incorrect or incomplete URL to the fetch()
function, the error
occurs due to your server responding with HTML and not JSON.
If you get a 404 Not found response when making the request, you have to correct the URL to which you're making the request or resolve the issue on your server side.
If you get a 500 Internal Server Error when making the response, debug the route on your server and check what causes the error.
To solve the "Uncaught SyntaxError: Unexpected token" error, make sure:
<script />
tag that points to an HTML file, instead of a
JS file.<script />
tag that points to an incorrect path.<script
tag.fetch()
method with an incorrect URL.