Introduction
When I tried to deploy a Next.js application to Vercel, I encountered a problem where the build succeeded locally but failed on Vercel. The error message was vague, and it was difficult to identify the cause.
In this article, I share the process from discovering the problem to resolving it, along with what I learned about JavaScript operator precedence.
Symptoms
Error Message
Characteristic Behavior
- Local build succeeds, but Vercel build fails
- Errors occur on different pages each time (22-03, 24-03, 25-04, etc.)
- Error details are hidden in production builds
Finding the Cause
While investigating multiple files, I discovered the following code pattern:
At first glance, it looks fine, but there was a pitfall of operator precedence lurking here.
What is Operator Precedence?
In JavaScript, operators have precedence. It is the same as in mathematics where “multiplication is calculated before addition.”
Precedence Example
Breaking Down the Problematic Code
This code is interpreted as:
When Environment Variables are Undefined
'' + undefined becomes the string 'undefined'. This is due to JavaScript’s type coercion behavior.
Why It Succeeded Locally
Because environment variables were set in the local environment, the problem did not occur:
In the Vercel environment, the environment variables were not set, so the string 'undefined' was generated, causing errors in subsequent processing.
Solution
Before Fix
After Fix
By removing the unnecessary '' +, the fallback processing now works as intended.
More Explicit Approach
You can also use parentheses to make the precedence explicit:
Lessons Learned
1. Be Aware of Operator Precedence
| Operator | Precedence |
|---|---|
() | 21 (highest) |
+ (string concatenation) | 13 |
| ` | |
?? (Nullish coalescing) | 4 |
2. Be Careful of Environment Differences Between Local and Server
- Just because it works locally doesn’t mean it will work on the server
- Always be aware of the presence or absence of environment variables
- Set default values carefully
3. Be Careful of Implicit Type Conversion
JavaScript performs type conversion automatically, which can lead to unintended results.
Summary
This bug was an operator precedence issue hidden in seemingly simple code.
You may not usually think about JavaScript operator precedence. However, caution is needed when combining multiple operators. When in doubt, I recommend using parentheses to write explicitly.