fix(form-data): fix ssr error due to window object access #373
+13
−7
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Background
The
form-data
package exports two entry points:The browser entry point is supposed to be used only in browser environment, which is why it accesses the
window
object:However, a lot of build tools (e.g. Vite) prefer the browser entrypoint during SSR. Due to this, we end up accessing the
window
object during SSR, which breaks rendering.This was reported in #212 previously, but the upstream package form-data doesn't have a fix for it.
I tried to revive the conversation about adding a fix for SSR failure in form-data, but don't think there'll be a fix from their side.
Fix
When we import from the package root like this
import FormData from 'form-data'
, we depend on the bundler for resolving the entry point correctly. This is why we can end up importing from thebrowser.js
entrypoint instead of theform_data
entrypoint.This can be fixed by directly importing from
form_data.js
, like this:import FormData from 'form-data/lib/form_data'
. For TypeScript support, I added a module declaration in theform-data.d.ts
file that re-exports the types from the library.Also added a check to fallback to the browser's
FormData
in case thewindow
object is not defined.