How do I fix error with svelte-kit and aws-amplify?

Viewed 503

I'm getting an error with svelte-kit and @aws-amplify/auth

import Auth from '@aws-amplify/auth'; causes the following error:


500

global is not defined

node_modules/amazon-cognito-identity-js/node_modules/buffer/index.js@http://localhost:3000/node_modules/.vite/@aws-amplify_auth.js?v=fb9b3a59:4766:5
__require2@http://localhost:3000/node_modules/.vite/chunk-A2XPJTG4.js?v=fb9b3a59:19:44
@http://localhost:3000/node_modules/.vite/@aws-amplify_auth.js?v=fb9b3a59:30155:32

I've tried adding this:

                resolve({
                    browser: true,
                    preferBuiltins: false,
                    alias: {
                        "./runtimeConfig": "./runtimeConfig.browser"
                    }
                }),

but it doesn't seem to do anything. Also I don't know what this runtimeConfig is

2 Answers

It's difficult, global exist in NodeJS and modern browsers but not in web-workers, but because Svelte heavily uses workers it's problem. https://github.com/sveltejs/svelte/pull/4628 -- This PR introduces globalThis but you need to find a way to change this lib.

Or if you want to use it in SSR only (server-side) you should import and put this code for <script context="module">.

The main issue here is this library because it depends on NodeJS and is not designed especially for browsers.

The solution from this Github issue fixed it for me... add this to the top of your app.html file:

<script>
    var global = global || window
    var Buffer = Buffer || []
    var process = process || { env: { DEBUG: undefined }, version: [] }
</script>
Related