amplify-js: Cannot use amplify-js in browser environment (breaking vite / snowpack / esbuild)
Describe the bug
The package aws-amplify is meant to be used in the browser, isnt it? Therefore it should not rely on node builtins, which sadly is the case and prevents the usage of this package in many js build tools like rollup, snowpack or vitejs.
The @aws-sdk package which is used by aws-amplify relies on various node build in modules like fs, process or http2, …
I described the issue also here (https://github.com/vitejs/vite/issues/1374) and Evan You the creator of vuejs and vite mentioned that webpack will drop support for node build ins in version five. Because webpack is used by tools such as create-react-app and vue-cli this will block many developers from using the amplify package soon I think!
To Reproduce Steps to reproduce the behavior:
- Download https://github.com/sem4phor/aws-cli-bug
- Run npm run dev (node required)
- See error in console
Expected behavior The package works in the browser and does not import any node build ins which are not available in browser environment.
Code Snippet https://github.com/sem4phor/aws-cli-bug
Screenshots
[plugin:vite:imports] Failed to resolve import "process". Does the file exist?
/Users/XXXXX/node_modules/@aws-sdk/util-user-agent-node/dist/es/index.js:1:22
1 | import process from "process";
| ^
2 | export function defaultUserAgent(packageName, packageVersion) {
3 | var engine = process.platform + "/" + process.version;
Error: Failed to resolve import "process". Does the file exist?
at TransformContext.error (C:\Users\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:59552:50)
at TransformContext.transform (C:\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:52957:30)
at async Object.transform (C:\Users\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:59742:30)
at async transformRequest (C:\Users\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:65977:29)
at async C:\Users\XXXXX\node_modules\vite\dist\node\chunks\dep-262f13eb.js:66068:32
What is Configured? Not relevant for this error.
- OS: Windows 10
- Browser: Chrome 87
- aws-amplify 3.3.13
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 100
- Comments: 120 (17 by maintainers)
Links to this issue
Commits related to this issue
- fix: resolve.alias for runtimeConfig Refs: https://github.com/aws-amplify/amplify-js/issues/7499#issuecomment-808503506 — committed to aws-samples/aws-sdk-js-notes-app by trivikr 3 years ago
- fix: add runtimeConfig resolver https://github.com/aws-amplify/amplify-js/issues/9639#issuecomment-1049158500 — committed to Milesq/ministry-sheet by Milesq 2 years ago
- Update with fix from https://github.com/aws-amplify/amplify-js/issues/9639#issuecomment-1081781840 — committed to kevinold/repro-vite-amplify by kevinold 2 years ago
YES!!! I’ve been stuck on this for days!!! Thanks to @armenr a couple comments up I was able to get things running with just ‘aws-amplify’ (haven’t tried with the components library yet) All i actually needed was to add
Then i can use aws-amplify and actually have the project build as normal
For the record i’m using Vite, React, TS. Bootstrapped the project with the vite react template.
"vite": "2.6.12","aws-amplify": "4.3.3"(now I’m just waiting for something else to go wrong as I progress through adding more functionality with amplify. Hope this helps you all that are struggling)
I found a workaround that can help for now. Eventually this will probably need to be fixed in the
@aws-sdkAdd a vite.confg.js file to the root of the project. You’ll need to add a new resolve.alias.
Then inside the index.html file add a script tag below the
<div id="app></div>but above the module script importYou need to set
window.globalandexports. If you don’t setwindow.globalit won’t work in development. If you don’t add invar exports = {}then it will build, but will throw an error when you open it up on your web browser.I made a branch here you can take a look at too. https://github.com/ErikCH/amplify-js/tree/hotfix/error-with-vite/.github/actions/bundle-size-action/vite
@Mootook correct me if I am wrong, but I don’t actually see you using aws-amplify in your repo (other than the package.json dependency)
If you insert the following code into
main.js:Then
npm run buildwill start failing withThis is the error message originally reported in the chain of issues: https://github.com/vitejs/vite/issues/1502 => https://github.com/vitejs/vite/issues/1374#issuecomment-754820938 => this
For
@sveltejs/kit@1.0.0-next.190withtypescript@4.4.4and@amplify/core@4.3.3(using Node 14), the following steps worked for me.For dev scripts, add the following to the top of the
<head>tag in app.html:For builds to succeed, add the following in the
config.kit.viteobject of svelte.config.js:And for preview runs, if you face an “Amplify.configure is not a function” error, change
Amplifyto a named import:@armenr solution worked for me with Vite + React + Amplify, updating index.html & vite.config.js with below
<script> if (global === undefined) { var global = window; } </script>resolve: { alias: { './runtimeConfig': './runtimeConfig.browser' } }Since this is still not resolved here are a few tips: As others already mentioned, you can fix these errors by adding the following config to
vite.config.jsThe above configuration will FAIL if you’re using React Router 6.4 data API.
You will have to stick to using React Router components.
Hope this helps some poor soul. God knows how much time I wasted figuring this out.
@ErikCH Honeslty I eventually solved this by getting rid of Amplify and just writing a light wrapper around
amazon-cognito-identity-jsand my own login form.Here it is if anyone wants to use it:
I had to update my Vite config to the following to get both build time & dev working (only the relevant parts of the config are included):
I have determined that the following modules cause build errors related to expecting various node js modules in the browser such as
httpandfs.We are working on removing the need for these manual configurations on Amplify, for now - for Vite customers can you try the workaround mentioned in this comment to see if that resolves build issues for you? https://github.com/kevinold/repro-vite-amplify/commit/4d6b42291dbbcc9cee08f0ec52b416efd5ed7145
I’ve been fighting this one for a few days and finally got it to work. This is what worked for me for vite and react.
Please don’t close this ticket without fixing the underlining issue.
I am facing the same issue while using
vite.I am getting the previously reported error
'request' is not exported by __vite-browser-external, imported by node_modules\@aws-sdk\credential-provider-imds\dist\es\remoteProvider\httpRequest.js. Is this something that is fixed? I have tried this with the latest version of aws-amplify3.3.22.I tried with rollup config as suggested earlier in this thread. I also experimented with
rollup-plugin-polyfill-node. Both of them fails to fix the issue.Here’s my
vite.config.jsError dump
I’m experiencing the same issue, I have had no luck finding a workaround. I am also using
vite. Also @sem4phor, in the issue body, you mention@aws-clibut I believe the problem is with@aws-sdk.configuring like this worked for me.
vite.config.js
export default defineConfig({ plugins: [vue()], resolve: { alias: { “./runtimeConfig”: “./runtimeConfig.browser”, //fix production build } } })
This solution also works in SvelteKit as well. Adding the
resolvebit to thesvelte.config.jsfile and adding the<script>tag to theapp.htmlfile (above all your other files) fixed everything!svelte.config.jsand the
app.htmlfileAnd depending on your specific setup, don’t forget to add your
aws-exports.jsfile. Mine looks like this:and then in my
__layout.sveltefile, I added:Still having trouble with Build
This works fine locally. I’m able to log in, log out, do all that fun stuff.
When I go to build the Sveltekit project with
npm run build, I get this error:Thank you, work for me
I second that. The problem seems to be in
@aws-sdkSeems like the library has dependencies on node built-in types which is really bad. Seems like the library was built for webpack and is not usable with vite or rollup at the moment? Also, the coupling increases the size of the package significantly.Are there any plans to get rid of the node dependencies anytime soon?
Temporary workaround that WORKS!
Tl;dr
Go to my example repo: https://github.com/armenr/amplify-vitesse-repro
Howdy folks! I’ve got a working setup for aynone that’s trying to get
@aws-amplify/ui-componentsworking with VITE + Vue3 - but it’s just slightly hacky, and I stumbled upon it TOTALLY by chance.Wanna give a shout out to @ErikCH for:
Wanna give another shoutout to @simlevesque for:
Are you ready kids?! (SpongeBob reference - feel free to disregard).
Notes before you dive in
I am working off of an increasingly popular (and honestly AMAZING) starter template called
VitesseWhy do I love vitesse? (recommend you go to the repo and see the readme for more extensive details)
Amplify-related caveats of Vitesse that I’ve discovered
amplify.ymlfile in your repo)Solution
Step 1:
vite.config.tsYou need to add the the
./runtimeConfigaliasYou need to add vue --> template --> compiler options
Added this, but not sure if it’s needed (please help me test if you’d like!):
My entire config -->
./modules/Amplify.tsSo, in Vitesse, there’s a concept of “modules” that is similar to “boot” files in the Quasar framework.
I created a “module” to load up Amplify on App boot, and this is where I use @simlevesque’s import workaround
Still not working! What happens next?
Once you get THIS far, you’ll see three IMPORTANT errors in your console/terminal
Error in console/terminal refers to
@stenciljs/coremissing a require/exportWe install
@stencil/coredirectly into our project -->pnpm install @stencil/coreError in console/terminal refers to
zen-observablemissing adefault exportpnpm install https://github.com/abdonrd/zen-observableHere, we’re installing a fork for zen-observable directly from a fork on GitHub that has a pending PR that the zen-observable maintainers are ignoring (the PR for this branch is neglected, but it works!)
Error in console/terminal refers to
bufferlibraryAdd package resolution overrides for
bufferin package.json (example covers pnpm and yarn)Final steps --> clear out your node_modules and re-install everything
rm -rf node_modulesin your project or your monorepo package folderpnpm installoryarnor whatever package manager you’re usingResults:
It’s funny because when I moved my code to your repo it’s all working but in mine it still failing. I’ve forked your repo with my code added in https://github.com/ebisbe/aws-vite-demo and my failing code in here https://github.com/ebisbe/skedr-prototype/tree/live
The error I get is:
@asmajlovicmars Looking at the repository, I saw some old
@aws-amplifyimports. You may want to double check those and switch them to named imports from version 3import { Analytics } from 'aws-amplify';.I did some tests and I might have found another work around for SvelteKit. To run in dev mode, take out ssr inside the config.
When I tested this allowed me to work in dev mode.
However, to build, I had to add it back in SSR. I also added in a few extra configurations into the config file, since it didn’t seem to pick them up from the HTML file. Here is the vite portion of the config.
With this configuration I was able to use Auth, after building and running it.
Here is a test repo with it working, make sure to add your Amplify configure exports.
The best way is to get rid of amplify and roll your own wrapper around
amazon-cognito-identity-js, tbh.To say that this is annoying would be an understatement.
This is a horrible developer experience. The least you could do is make this lack of integration support known up front so we don’t waste our time on another amplify product.
My silly workaround for a static site with some TypeScript, but without Webpack was to import the entire library into my “main” file:
Am using pure Vite+React and whilst the above solved the build, I now get this in browser:
The yellow warnings are actually mine so it looks like in some way Amplify is loading, however that’s as far as it gets.
😦
Here is my
vite.config.ts@asmajlovicmars In your
svelte.config.cjsimport yourresolve.aliaslike thisstill getting this for me:
> 'request' is not exported by __vite-browser-external, imported by node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.jsthanks this worked for me
Having the same issue with SvelteKit and Amplify, and not including aws-sdk. Just Amplify js, but aws-sdk is called implicitly, as a dependency I guess…
request’ is not exported by __vite-browser-external, imported by node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js file: /Users/asmajlovic/code/sveltekit/p1/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js:4:9 2: import { ProviderError } from “@aws-sdk/property-provider”; 3: import { Buffer } from “buffer”; 4: import { request } from “http”; ^ 5: /** 6: * @internal
@sammartinez I am using amplify which has aws-sdk as it’s dependency (see reproduction repository)
The vue label is kinda wrong. It is an issue with js bundlers which use native ecmascript modules. Vite is not vue-only.
ugh whatever I’m going back to CRA then.
npm install --save-dev rollup-plugin-polyfill-node vite.config.js
I confirm this works in Sveltekit with ‘@aws-amplify/api’, ‘@aws-amplify/auth’, ‘@aws-amplify/core’ 🙏🏼
@mgerring We ended up replacing it (and eventually replacing Amplify), it isn’t a hugely horrible thing to do, took us about a day though we don’t cover all states. There are a many other reasons other than this ticket to not use
@aws-amplify/ui-reactand also Amplify entirely.The sooner you migrate to a lightweight promise based wrapper around the parts of
amazon-cognito-identity-jsyou actually need, the sooner your headaches will disappear 😃I still saw it with:
adding the following to
vite.config.tssolves it:Without this change, it still fails and the error clearly points to @aws-amplify/ui-react:

I was told during Amplify Office Hours that v6 introduced a fix for Vite environments that removes the need to add this resolve config:
The release of v6 may or may not address everything discussed in this issue, but it felt appropriate to share this update here.
Still open in 2023 with newest Quasar (vite). and newest amplify:
Tried to use rollup-plugin-polyfill-node but quasar.config.js runs in a node env. so I can’t import it. require does not work either. Any ideas to manage it with quasar and vite somehow ?
This is the origin error when I run npx quasar build :
'request' is not exported by __vite-browser-external, imported by node_modules/@aws-sdk/client-cloudwatch-logs/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js file: /Users/sc/dev/artbarrack/code/node_modules/@aws-sdk/client-cloudwatch-logs/node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js:4:9 2: import { ProviderError } from "@aws-sdk/property-provider"; 3: import { Buffer } from "buffer"; 4: import { request } from "http"; ^ 5: /** 6: * @internal /Users/sc/dev/artbarrack/code/node_modules/rollup/dist/shared/rollup.js:198 base = Object.assign(new Error(base.message), base);This also affects many vite-plugin-ssr users.
I got both dev and prod builds working with @ffxsam 's solution - thanks!
My whole
vite.config.ts(with Vuetify):Polyfilling node APIs worked for me.
Rollup plugin mentioned here might be worth looking at.
Hey all, I don’t know if this helps, but I paid someone to come up with a solution so that AWS Amplify would work within Nuxt 3 (which uses Vite under the hood).
This is the code he wrote. This is way over my head, but it looks like it’s a custom Vite plugin. BTW, this is just a workaround until AWS fixes stuff on their end. I’ve talked with the Amplify team, and they fully intend to update their SDK to use some of the more modern features of Node.js like import/export maps, and using proper ESM, which will fix these issues.
https://github.com/aws/aws-sdk-js/issues/3673 seems to be along similar issues. I too am seeking solutuin for sveltekit + aws-amplify and using I believe the correct “adapter” (new to this part) but as mentioned in the linked issue https://ui.docs.amplify.aws/ui/getting-started/installation?platform=vue seams to have a soltution for vite in vue but of course svelte has its own way of doing this. Does anyone know the “translation” of this to sveltekit?
I have in my app.html
which seems equivalent to their recommended vue index.html of
Next the config. I have in my svelte.config.js which i added adapter-node (which again im new to) https://github.com/sveltejs/kit/tree/master/packages/adapter-node
The amplify fixes for vue vite say make vite.config.ts
I’m not sure what the translation to svelte.config.js would be
Then lastly they add to tsconfig.json
Appreciate all help and people that have figured this stuff out thus far
@ErikCH and for anyone else who might find it useful --> here’s a reproducible sample repo
https://github.com/armenr/amplify-vitesse-repro
ping - added
feature-requestlabel so stalebot skips.I was able to reproduce that as well @radiosilence .
A quick work around is don’t use the
@aws-amplify/ui-reactlibrary. Use theaws-amplifylibrary instead. You’ll have to create your own UI, but it should work. Here is the guide to the API https://docs.amplify.aws/lib/q/platform/jsI think to be reprouced relates to a maintainer who needs to reproduce this. I have already submitted a reproduction repository…
Moreover the label Amplify UI Components is wrong, too IMO. The issue persists without importing ui components @sammartinez
I too am having this issue. I have imported
@aws-sdk/client-cognito-identityand@aws-sdk/credential-provider-cognito-identitydirectly. I am using Vite and not using Amplify fyi. Hopefully that helps you track down the root cause.@TeoTN thanks for your feedback, it seems that it may be specific to the UI library. Will do additional testing and confirm.
With the release of the latest major version of Amplify (aws-amplify@>6), this issue should now be resolved! Please refer to our release announcement, migration guide, and documentation for more information.
If you are still facing this issue after upgrading to v6, please let us know with a reply back.
Good to hear! It seems like this issue might be solved/closable if it resolved this issue.
@charlieforward9 v6 works perfectly out of the box with SvelteKit, just tested it today, but there’s another problem with SSR, which I don’t know how to solve yet, described it here: https://github.com/aws-amplify/amplify-js/issues/12578 .
There’s no more withSSRContext, so I need to figure out how to get cognitoUser on the server side… Otherwise, v6 looks good to me.
For Quasar I had to add it to the build section in
quasar.config.js(extending the vite config didn’t work).The missing global definitions is added directly inside
index.htmlThanks! this helped, here’s my vite.config.vue
@mkilp, I just went through the same path of converting from CRA to Vite. Same issues, dev worked, production build crashed with error about Crypto. I also tried some of the various npm poly fill packages I see that you have as well.
I ended up doing a clean Vite install with a new amplify project and moved my project over piece by piece. Then copied the vite.config.js back to my original project. Below is my vite.config.js file. It turned out to be much simpler setup than all the various things I tried. I think that a lot of the poly fill packages were used for earlier versions of vite/amplify and are no longer needed. (I think, not sure about that)
Note: the setupTests.js file in the test section @imports testing-library/jest-dom for vitest.
And I also, deleted npm_modules and the package-lock.json file to make sure the setup was clean as possible. I had other issues from the package-lock.json file so I don’t know if it effected the vite config.
It has been working fine for about a mouth with several deploys to production. Although it was so much more work than I expected, I am happy I did it.
Hope this will help.
Regards,
vite.config.js
import { defineConfig } from ‘vite’ import react from ‘@vitejs/plugin-react’ import rollupNodePolyFill from “rollup-plugin-node-polyfills”;
// https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], define: { ‘process.env’: {} }, optimizeDeps: { esbuildOptions: { // Node.js global to browser globalThis define: { global: “globalThis”, //<-- AWS SDK }, }, }, build: { rollupOptions: { plugins: [ // Enable rollup polyfills plugin // used during production bundling rollupNodePolyFill(), ], }, }, test: { globals: true, setupFiles: ‘setupTests.js’, }, resolve: { alias: { ‘./runtimeConfig’: ‘./runtimeConfig.browser’, // <-- Fix from above }, } })
@pedersenderekserif - we understand this is not ideal, and are actively working on removing the need for additional configurations when using our library. We have also enriched our documentation with the steps you would need to get started with a Vue/Vite project.
@abdallahshaban557 Yes this worked for me with aws-amplify 3.3.7, i.e., quite an old version.
@dancingfrog Thanks for that solution, it is working for me for
vite build, however for local dev there is a console error thrownUncaught ReferenceError: aws_amplify is not defined. Did you get it to work for your dev server?Edit: disregard my question, it was due to outDir being set to “…/dist” and not having access to the upper folder in dev mode
Thank you @armenr.
@armenr Awesome! Thanks for the great work around!
@vovawed No, I haven’t yet found the solution… As a workaround, I am using snowpack to do my production builds. Snowpack has a built-in support for node-polyfills with
snowpack build --polyfill-node.As commented here. This should have been fixed in this library by isolating node related code. However, it doesn’t seem to have happen.
@sammartinez Would you have any update on this issue?