How to fix SyntaxError: Unexpected token in Node.js

Node.jsBEGINNERMEDIUMUpdated Dec 9, 2025ยท 254 views

This error occurs when the JavaScript parser encounters a token it does not recognize at the given position. It typically indicates missing brackets, quotes, semicolons, invalid characters, or syntax violations that prevent the code from being parsed correctly.

Quick fix

Fixes ERR_PARSE

function getData() {
  const data = fetchData();
  // Missing closing brace here

  console.log(data); // <- Error reported here
  1. Check the error line and surrounding context
  2. Use a linter to identify the exact problem
  3. Fix bracket and parenthesis mismatches
  4. Check for unclosed strings
node.js โ€” error
function getData() {
const data = fetchData();
// Missing closing brace here
console.log(data); // <- Error reported here
SyntaxError: Unexpected token

What this error means

The "Unexpected token" syntax error indicates that the JavaScript parser found a piece of code that violates the language's syntax rules. The parser reads your code token by token and expects specific patterns based on JavaScript grammar. When it encounters something unexpected, it cannot continue parsing and throws this error. The specific location and token vary depending on what went wrong. Common culprits include: - Missing or mismatched brackets, parentheses, or braces - Unclosed string literals - Invalid operator placement - Reserved keywords used as variable names - Invisible characters from copying code - Type annotations without proper transpilation The error message often includes the approximate line number where the parser stopped, though the actual problem may be on the preceding lines.

Typical symptoms

  • Application fails to start with a parse error immediately on load
  • Error message shows "SyntaxError: Unexpected token" followed by a character or token name
  • Build tools or linters report syntax errors in the file
  • Code that worked in one environment fails in another
  • Error appears after copying code from a website or PDF
  • Changes to one line cause errors on lines far away

Common causes

  1. Missing closing bracket, parenthesis, or brace (most common)
  2. Unclosed string literal - missing closing quote
  3. Extra or mismatched brackets/parentheses
  4. Missing comma between function parameters or object properties
  5. Using reserved words (if, for, while, class, etc.) as variable or function names
  6. Invalid characters pasted from Word processors or PDFs (smart quotes, zero-width spaces)
  7. Incorrect arrow function syntax or misplaced operators
  8. Missing semicolons in certain contexts (though usually optional)
  9. JSON parsing error - trying to parse invalid JSON as JSON
  10. TypeScript or JSX syntax in plain JavaScript without proper transpilation

How to fix "SyntaxError: Unexpected token"

1Check the error line and surrounding context

The error message includes a line number where the parser failed. Check that line and the few lines before it.

The actual problem is often 1-5 lines before the reported error line. The parser only realizes there's a problem when it encounters the unexpected token.

Common examples:

Missing closing brace (error reported on line 5, problem on line 2):

javascript
function getData() {
  const data = fetchData();
  // Missing closing brace here

  console.log(data); // <- Error reported here

Unclosed string (error reported on line 3):

javascript
const message = "Hello World; // <- Missing closing quote
const name = "John
console.log(message); // <- Error reported here

Extra bracket:

javascript
const arr = [1, 2, 3];]  // <- Extra bracket here
console.log(arr); // <- Error reported here
2Use a linter to identify the exact problem

Linters like ESLint can pinpoint syntax errors more clearly than runtime errors.

Install ESLint:

bash
npm install --save-dev eslint
npx eslint init  # Follow the prompts to set up

Run ESLint on your file:

bash
npx eslint your-file.js

ESLint output is typically more detailed:

bash
file.js
  1:34  error  Parsing error: Unexpected token )

1 | function getData(a, b,) {
  |                         ^

This clearly shows there's an extra comma before the closing parenthesis.

In VS Code:
- Install the ESLint extension
- Problems will show directly in the editor with red squiggles
- Hover over the error for more details

3Fix bracket and parenthesis mismatches

Balance all brackets, parentheses, and braces.

Before (incorrect):

javascript
function getData() {
  const data = [1, 2, 3;  // <- Wrong bracket type
  return data
// Missing closing brace

After (correct):

javascript
function getData() {
  const data = [1, 2, 3];  // <- Correct bracket type
  return data;
}

Use an editor with bracket matching:
- Place cursor on an opening bracket and it highlights the closing one
- Most editors (VS Code, WebStorm, Sublime) support this
- Use keyboard shortcuts to jump between matching brackets

Common bracket pairs:
- ( ... ) - Function calls, grouping
- [ ... ] - Arrays, indexed access
- { ... } - Objects, blocks, statements

4Check for unclosed strings

Ensure all string literals have matching quotes.

Before (incorrect):

javascript
const name = "John;
const city = 'New York;
const message = `Hello`;  // backticks don't match quotes above

After (correct):

javascript
const name = "John";
const city = 'New York';
const message = `Hello`;

Important: Match quote types:

javascript
"string with double quotes"   // Correct
'string with single quotes'   // Correct
`string with backticks`     // Correct
"mismatched quote'            // WRONG

Check for smart quotes:
If you copied code from a website, Word document, or PDF, it may contain "smart quotes" instead of regular quotes.

Wrong (from Word/PDF):

javascript
const message = "Hello";  // These are fancy curly quotes

Right (plain text):

javascript
const message = "Hello";  // These are straight quotes

Fix: Delete the string and retype it manually in your editor, or paste into a plain text editor first.

5Fix invalid character and encoding issues

Remove invisible or invalid characters, especially from pasted code.

Check for invisible characters:

bash
# Show all whitespace characters (including invisible ones)
cat -A your-file.js | head -20

# Look for unusual characters like zero-width spaces, special unicode
hexdump -C your-file.js | head -20

Common culprits when pasting:
- Smart quotes from Word: curly quotes (replace with regular straight quotes)
- Zero-width spaces (from some web interfaces)
- Em dashes and en dashes (replace with -)
- Tab characters mixed with spaces

Solutions:
1. Delete the problematic line and retype manually
2. Paste into a plain text editor first (Notepad, plain text mode)
3. Use your editor's find-and-replace to swap smart quotes with regular quotes

Using sed to clean common issues:

bash
# Replace smart quotes with regular quotes
sed -i 's/[""]/"/g; s/['']/'"'"'/g' your-file.js
6Check for reserved word misuse

Do not use JavaScript reserved words as variable or function names.

Reserved words you cannot use:

javascript
// Cannot use as names:
const if = 5;        // WRONG
const class = {};    // WRONG
function for() {}    // WRONG
let while = true;    // WRONG

Legal alternatives:

javascript
// Correct versions:
const ifCondition = 5;
const myClass = {};
function loop() {}
let whileActive = true;

Complete list of reserved words:
Abstract, arguments, await, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, eval, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, interface, let, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, void, volatile, while, with, yield

Context matters: Some reserved words can be used in specific contexts (like as object properties):

javascript
const obj = {
  class: 'main',  // OK as object property
  for: function() {},  // OK as object property
};

console.log(obj.class);
7Verify JSON is valid JSON

If parsing JSON, ensure the data is actually valid JSON, not HTML or malformed data.

Common issue - server returns HTML instead of JSON:

javascript
// If your server returns an error page as HTML
const response = await fetch('/api/data');
const json = await response.json();  // <- Error if response is HTML

Fix - check content type first:

javascript
const response = await fetch('/api/data');

if (!response.ok) {
  throw new Error(`HTTP ${response.status}`);
}

if (!response.headers.get('content-type')?.includes('application/json')) {
  throw new Error('Response is not JSON');
}

const json = await response.json();

Validate JSON structure:

javascript
// Valid JSON
{
  "name": "John",
  "age": 30,
  "items": [1, 2, 3]
}

// INVALID JSON - trailing comma
{
  "name": "John",
  "age": 30,  // <- Extra comma not allowed
}

// INVALID JSON - single quotes
{
  'name': 'John'  // <- Single quotes not valid in JSON
}

// INVALID JSON - unquoted keys
{
  name: "John"  // <- Keys must be quoted in JSON
}

Test JSON validity:

bash
# Use jq to validate JSON
echo '{"name":"John"}' | jq .

# Pretty-print and validate
curl https://api.example.com/data | jq .

Advanced notes

Parser Recovery:

Modern JavaScript engines try to recover from syntax errors gracefully, but the process varies. Node.js stops parsing immediately upon encountering an unexpected token and will not execute any code in that file. Some bundlers and transpilers may attempt recovery or partial parsing.

Transpilation Requirements:

If using TypeScript, JSX, or stage-proposal syntax, ensure your build tool is configured correctly:
- TypeScript: Run tsc or tsx instead of node directly
- JSX: Use @babel/preset-react or @swc/preset-react
- Modern syntax: Configure your transpiler target appropriately

Error Position Accuracy:

The line number reported is where the parser failed, not necessarily where the problem is. For complex expressions or nested structures, the error can appear several lines after the actual issue. Use binary search: comment out half your code, run it, and narrow down the problem.

Debugging Strategy:

1. Copy the exact error message and search for it
2. Check the file immediately before the reported line
3. Use a linter (ESLint, TypeScript) for faster feedback
4. Test incrementally - write code in small chunks
5. Use an IDE with real-time syntax checking
6. Never ignore squiggly red lines in your editor

Common Patterns:

- Copy-paste errors: Always verify code copied from websites
- Merge conflicts: After git merge, check for conflict markers
- File encoding: Ensure files are UTF-8 without BOM
- Mixed line endings: Use LF consistently, not CRLF

Frequently asked questions

What does "ERR_PARSE" mean?
The "Unexpected token" syntax error indicates that the JavaScript parser found a piece of code that violates the language's syntax rules. The parser reads your code token by token and expects specific patterns based on JavaScript grammar. When it encounters something unexpected, it cannot continue parsing and throws this error.
How do I fix "ERR_PARSE"?
This error occurs when the JavaScript parser encounters a token it does not recognize at the given position. It typically indicates missing brackets, quotes, semicolons, invalid characters, or syntax violations that prevent the code from being parsed correctly.
What causes "ERR_PARSE"?
Missing closing bracket, parenthesis, or brace (most common) Unclosed string literal - missing closing quote Extra or mismatched brackets/parentheses
Is the "ERR_PARSE" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading