Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(form-data): fix ssr error due to window object access #373

Merged
merged 2 commits into from
Oct 16, 2024

Conversation

vaibhavrajsingh2001
Copy link
Contributor

Background

The form-data package exports two entry points:

"main": "./lib/form_data",
"browser": "./lib/browser",

The browser entry point is supposed to be used only in browser environment, which is why it accesses the window object:

module.exports = typeof self == 'object' ? self.FormData : window.FormData;

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 the browser.js entrypoint instead of the form_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 the form-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 the window object is not defined.

@filfreire filfreire merged commit 66b587b into Kong:master Oct 16, 2024
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants