commercetools-sdk-typescript
commercetools-sdk-typescript copied to clipboard
Different transpiled codes is produced for browser and server
I'm trying to use the typescript sdk in nextjs middleware. The nextjs middleware is running Edge runtime, which is a browsed-based web API. My app is running on nodejs server, but for nextjs middleware it is a browser-based runtime.
When trying to create new sdk, the following transpiled code is being called in a file commercetools-sdk-client-v2.browser.cjs.js
const isBrowser = () => window.document && window.document.nodeType === 9;
From checking the repo, this file is transpiled from this code https://github.com/commercetools/commercetools-sdk-typescript/blob/650e5766262ffb1bf3e1f123239c2be4fa254ed9/packages/sdk-client/src/http-user-agent/create-user-agent.ts#L11
As you could see, the transpiled code for browser has no checking for typeof window !== 'undefined'
.
When checking the transpiled version for server, it does have the check (commercetools-sdk-client-v2.esm.js
)
const isBrowser = () => typeof window !== 'undefined' && window.document && window.document.nodeType === 9;
Next.js middleware picks the browser-based file, but at the same time it is running on the server. This is expected behaviour of nextjs. As the result, it does not have window
and the call window.document
fails.
Why the transpiled code is different for server and client? Can you add the check for browser file as well?
Hi @lojzatran
I want to assume this check typeof window !== 'undefined'
is irrelevant for the reason that the file .browser.cjs.js
and .browser.esm.js
are both expected to run in a browser environment thus making the check redundant.
However, I have opened up an issue here to know why this is the case for sure and if there is a way to prevent it.
Thanks
Hi @lojzatran
We got a response from the team behind Preconstruct
and here is what they said.
Basically you can try to make the check before calling the nextjs middleware or tell the nextjs middleware to pick the .esm
build or even better avoid the browser build and use the .esm
or .cjs
build all through.
Note, closing this issue, feel free to ope again if you have further questions.
Thanks