SyntaxError: Unexpected Token

Shivan M.

The Problem

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:

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

Checking Server Responses

You might encounter this error with the following message:

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:

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( } }

Additional Resources

Get Started With Sentry

Get actionable, code-level insights to resolve JavaScript performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a JavaScript project and note your DSN

  3. Grab the Sentry JavaScript SDK

<script src=""></script>
  1. Configure your DSN
Sentry.init({ dsn: 'https://<key><project>' });

Loved by over 4 million developers and more than 90,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.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

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