Fix: 'Uncaught SyntaxError: Unexpected token <' in JavaScript: A Complete Beginner’s Guide

Encountering the 'Uncaught SyntaxError: Unexpected token <' is a rite of passage for web developers. This error typically happens when the browser attempts to execute a file as JavaScript, but the file actually contains HTML. Since HTML starts with a < character (like <!DOCTYPE html>), the JavaScript engine gets confused and throws a syntax error. Here is a step-by-step guide to identifying and fixing this common issue.

Step 1: Verify the Script Source Path

The most common cause is an incorrect file path in your <script> tag. If the browser cannot find the .js file at the specified location, the server often returns a 404 Error Page (which is HTML). The browser then tries to parse this 404 HTML page as JavaScript.

  • Check your code for: <script src="js/main.js"></script>
  • Ensure the file actually exists in that folder.
  • Pro-tip: Open the Network tab in your browser's Developer Tools (F12), refresh the page, and check if any .js files are returning a 404 Status.

Step 2: Check for Relative vs. Absolute Paths

If you are using a routing system (like in React, Vue, or a custom Express server), a relative path might fail when you navigate to a sub-page. For example, if you are on yourdomain.com/blog/post-1, a relative script path like src="app.js" will look for the file at /blog/app.js instead of the root.

The Fix: Always use an absolute path by adding a leading slash: <script src="/app.js"></script>. This ensures the browser always looks in the root directory.

Step 3: Inspect the Server's Content-Type Header

Sometimes the file exists, but the server is sending it with the wrong MIME type. JavaScript files must be served with Content-Type: application/javascript. If your server sends it as text/html, the browser may misinterpret it.

  • In Chrome DevTools, go to the Network tab.
  • Click on the JavaScript file.
  • Look at the Response Headers section to confirm the Content-Type.

Step 4: Resolve Single Page Application (SPA) Routing

In SPAs (like React or Angular), if you refresh a page on a deep link (e.g., /dashboard/settings), the server might be configured to serve index.html for all routes. If your script tags use relative paths, the server will send the index.html file instead of the actual script, leading to the 'Unexpected token <' error.

The Fix: Ensure your publicPath is set to / in your Webpack or Vite configuration, and ensure your HTML <base href="/"> tag is set correctly if you are using one.

Step 5: Check for Typos in HTML Files

Sometimes, we accidentally wrap JavaScript code inside a <script> tag that points to an external file, or we put HTML inside a .js file. Ensure that your .js files contain only valid JavaScript and no HTML tags like <div> or <script> themselves.


💡 Pro Tip: Keep your software updated to avoid these issues in the future.


Category: #Website