Sentry Answers>JavaScript>

SyntaxError: Unexpected Token

SyntaxError: Unexpected Token

Shivan M.

The ProblemJump To Solution

The SyntaxError: Unexpected token error in JavaScript indicates that a specific language construct was expected, but something else was found. Why might I encounter this error?

The Solution

This usually happens because of a typo or, in some cases, because a server or third-party service returned an unexpected response.

Fixing Typos

If this error occurs because of a typo, it is a good idea to look for code that is supposed to contain a specific language construct, for example, opening and closing braces, quotation marks, and semicolons.

In the example below, the for loop has a comma preceding the semicolon. In this case, JavaScript expected a semicolon but found the comma instead, resulting in an error:

Click to Copy
for (let i = 0; i < 5,; ++i) { console.log(i); }

Checking Server Responses

You might encounter this error with the following message:

Click to Copy
Syntax error: unexpected token <

In this case, it is likely that the cause of the error is a server response that is expected to be a JSON value, but has instead returned HTML.

An instance where this might occur is when a server returns a 404 page with an HTTP 200 response code.

In this scenario, the server responded with an HTML page including a 404 response, but the response status code was 200. If your code parses this response as JSON, you will encounter the above error.

This can also occur if a backend server responds with an error that is HTML formatted, with a response code that your application treats as valid. The following code example illustrates how this might happen:

Click to Copy
async function getPosts() { const posts = await fetch('/api/posts'); if (response.status === 200) { // if the server responded with a 200 OK with an HTML formatted error, this will raise an exception const postsData = JSON.parse(response.data) } }

Additional Resources

  • ResourcesImprove Web Browser Performance - Find the JavaScript code causing slowdowns
  • ResourcesJavaScript Frontend Error Monitoring 101
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Loved by over 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.