amplify-ui
amplify-ui copied to clipboard
SvelteKit support
Is this related to a new or existing framework?
New framework
Is this related to a new or existing API?
No response
Is this related to another service?
No response
Describe the feature you'd like to request
I along with many others are running into some issues trying to use sveltekit with aws amplify. I'm not sure if there is a formal feature request to get support for it or if it is being worked on to be supported by aws amplify.
Describe the solution you'd like
Ui components could be good eventually but even just getting it to work more easily or have simple guide would be great. I've managed to get around many of the gotchas but can't get it to build. Even if I somehow figure this part out it seams like there should be a more guided approach for using sveltekit with aws amplify
Describe alternatives you've considered
https://github.com/aws/aws-sdk-js/issues/3673 aws-amplify/amplify-js#9639 https://github.com/aws-amplify/amplify-console/issues/1298 https://github.com/aws-amplify/amplify-console/issues/2318 https://github.com/aws-amplify/amplify-js/issues/9056
Additional context
No response
Is this something that you'd be interested in working on?
- [ ] 👋 I may be able to implement this feature request
- [ ] ⚠️ This feature might incur a breaking change
@24jr Could you detail us some of the workaround you did and why you have to do it? Right now, we are also waiting on https://github.com/aws/aws-sdk-js/issues/3673. (Side note: Erik who opened up the issue is from our team). But if you have other things you think can be done in amplify that can unblock svelte usage, we would like to learn more of this.
Yeah that one was one I looked at and I don't want to repeat stuff of course but not sure if there was really a sveltekit focused issue to find solution but rather a mish mash of a bunch of things. So for me this is where I'm at. I'll just go over everything best I can remember
Standard skeleton svelte-kit project https://kit.svelte.dev/
npm init svelte@next my-app
cd my-app
npm install
I used aws amplify admin ui to create my backend so ran (of course this first npm install -g @aws-amplify/cli
)
amplify pull --appId d2zuoroq5jzalo --envName staging
p.s. make sure your default browser set to chrome not brave or won't work when login prompt shows
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using none
? Source Directory Path: src
? Distribution Directory Path: dist
? Build Command: npm run-script build
? Start Command: npm run-script start
? Do you plan on modifying this backend? No
Pretty much just kept the defaults for all. of course no sveltekit option for js framework so kept as javascript. However the last choice was important to say No for plan to modify. because if I say yes it fails with
? Do you plan on modifying this backend? Yes
✔ Successfully pulled backend environment staging from the cloud.
✖ There was an error initializing your environment.
Failed to pull the backend.
Must use import to load ES Module: /Users/24jr/Documents/projects/2021/svelte/agility-all/agility/src/aws-exports.js
/usr/local/lib/node_modules/@aws-amplify/cli/node_modules/amplify-frontend-javascript/lib/frontend-config-creator.js:1
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/24jr/Documents/projects/2021/svelte/agility-all/agility/src/aws-exports.js
I don't need to update the backend directly in the app so this was not a big deal. Selecting No was fine and worked. When I wanted update the graphQL schema lets say I would go to an empty folder outside of sveltekit proj and do the same amplify pull --appId d2zuoroq5jzalo --envName staging
and say yes in that and it would succeed and I could make changes to schema from there. I didnt do anything other than update schema like this.
To get amplify to work in the app I added to app.html
<script>
const isBrowser = () => typeof window !== 'undefined';
const isGlobal = () => typeof global !== 'undefined';
var exports = {};
if (!isGlobal() && isBrowser()) {
var global = window;
}
</script>
I put the Amplify imports in the __layout.svelte route because my understanding is it's a main part of every page and context="module" runs first
<script context="module">
import "../app.css";
import Layout from "$lib/views/Layout/index.svelte";
// import Amplify from "aws-amplify";
import { Amplify } from '@aws-amplify/core'
import awsExports from "../aws-exports";
Amplify.configure({ ...awsExports, ssr: true });
import { initAuth } from "$lib/components/Auth/store";
initAuth();
</script>
I believe was having some issue with import Amplify from "aws-amplify";
however import { Amplify } from '@aws-amplify/core'
worked as alternative
From this point everything worked fine in the app with authentication and making mutations and queries to my backend as usually done with API.graphql(...
To build I used adapter-static from https://github.com/sveltejs/kit/tree/master/packages/adapter-static
npm i -D @sveltejs/adapter-static@next
My resulting svelte.config.js file looked like
/** @type {import('@sveltejs/kit').Config} */
import adapter from '@sveltejs/adapter-static';
export default {
kit: {
target: '#svelte',
adapter: adapter({
pages: 'build',
assets: 'build',
fallback: null
}),
vite: {
resolve: {
alias: {
'./runtimeConfig': './runtimeConfig.browser',
},
},
},
}
};
alias: { './runtimeConfig': './runtimeConfig.browser', }
part had to be done for it to successfully build with amplify
Now phew got through this stuff. npm run build
creates build folder successfully npm run preview
runs app successfully. Ok push to github and in admin ui add the front end to existing backend and fails. Then was looking into using the amplify.yml to make it potentially work and this is where landed though still didn't work
version: 1
env:
variables:
USER_BRANCH: staging
backend:
phases:
build:
commands:
- '# Execute Amplify CLI with the helper script'
- amplifyPush --simple
frontend:
phases:
preBuild:
commands:
- npm install
build:
commands:
- npm run build
artifacts:
baseDirectory: build
files:
- '**/*'
cache:
paths:
- node_modules/**/*
Error in amplify build process is long but important part assuming is
2021-11-15T22:27:51.722Z [WARNING]: ✔ Successfully pulled backend environment staging from the cloud.
2021-11-15T22:27:51.745Z [WARNING]: ✖ There was an error initializing your environment.
Then I saw Rich Harris the main svelte guy was going to be working on svelte and be backed by vercel so I was like I have no idea what that is but if they like sveltekit then lets check it out. And they did hosting so tried that and successfully got sveltekit projects working however not with my amplify backend and wouldnt be able to find ../aws-exports.js which is because it was in gitignore which explicitly says dont edit this and I'm not super well versed on the exact procedures with that so that didn't work and josef in the discord group who seems pretty smart and helpful said I could look into doing a bash script but he hasnt tried that and not sure if it will work. I don't even know what a bash script is so kindof just stuck hoping some sveltekit community beauties somehow pull through and eventually a person smarter than me figures this out.
This is my kind of base project was trying to use https://github.com/24jr/agility
and this was only backend thing which made in amplify ui. Also had email cognito auth and optional mfa
If need more detail lmk I'll try and help best I can. May have forgot something here or there. Also want to look at my auth component I spent a long time on that could help if making ui components for sveltekit at some point
these are what appear to be preliminary next docs and for vue mentions vite instructions https://ui.docs.amplify.aws/getting-started/installation?platform=vue#vite
@24jr Thanks for the very detailed summary. This is super useful. To support svelte, it would be cross team effort and some help from SDK side as well. We have this discussion in our UI framework - https://github.com/aws-amplify/amplify-ui/discussions/469
I am going to move this issue to UI since they will be helping with the framework and if there are bits that needs to be implemented on JS and Console we will work with them to get this one.
@ashika01 Ok great oh yeah I think I came accross that at one point but looked outdated and also not sure if sveltekit requires different setup than general svelte but seems like sveltekit will be the predominant usage of svelte. I so much appreciate your help in helping progress this to next steps!
Hi @24jr
I really enjoy SvelteKit, and though we have not officially supported it yet in our updated UI library, we are looking at possibly adding it for the future.
I'm glad you've been able to find a workaround for most of the issues, but you're stuck on this one now?
Ok push to github and in admin ui add the front end to existing backend and fails.
So it's not deploying?
@ErikCH long time fan. I always say that to you lol. Yeah the hosting build fails. And awesome to hear you guys looking to add svelteKit. I would love that.


There was an error initializing your environment.
And I believe is same issue noticed when amplify pull project in and choose to update backend locally which I found alternative in updating the schema but I'm guessing they relate
@24jr Thanks!
Alright, lots of good information. I'll see if I can reproduce this, I'll add feedback to this issue as soon as I can.
Hey @24jr and @ErikCH saw the update to this issue and wanted to chime in. I believe what we are experiencing with the build error is due to this issue from the CLI https://github.com/aws-amplify/amplify-cli/issues/5691. As a workaround I've leveraged yarn workspaces (with yarn 1.x) to move the SvelteKit app to its own workspace. This allows us to use "type": "module"
in the app's package.json
as we see with SvelteKit sites, and after making this adjustment we can update our buildspec accordingly to deploy a static SvelteKit site
reference:
- SvelteKit site in it's own workspace https://github.com/josefaidt/amplify-discord-bots/tree/main/packages/app
- buildspec adjustment https://github.com/josefaidt/amplify-discord-bots/blob/main/amplify.yml#L8-L14
For the aws-exports
import issue, I would recommend changing the src
directory of your Amplify project to point to a workspace that does not have "type": "module"
in the package.json
, however we can use an exports
declaration in a workspace's package.json
to allow us to import given the context. In this example we are saying if we "import" this package, import the aws-exports
file. Since this file is already written using ESM it will allow us to import the exports file into an ESM project like SvelteKit
import awsConfig from '@my/aws-exports'
@ErikCH Were you by chance able to find a good way to do this?
@24jr !
Did this comment help with the build errors?
What I'm looking into is adding Svelte to our Authenticator UI library. That way you can use Svelte and easily add in the latest and greatest Authenticator (and soon Chatbot and Storage components). That's on the horizon soon!
After that is in place, we'll take a look at other places in the Amplify ecosystem that Svelte support is needed.
Does that make sense?
@ErikCH I am going to try that tomorrow. Yeah makes sense to so have an auth component to be able to help test some stuff easier. I built my own https://github.com/24jr/agility/tree/main/src/lib/components/Auth . I know for vercel there is adapter-vercel and adapter-netlify idk if we just need an adapter-amplify. It's the build process that I'm stuck at now. Idk what yarn workspaces is but I'll give that a shot as @josefaidt suggested.
But cool pumped to hear there is some progress being made with svelte-kit! I am thankful for you @ErikCH !
Oh I see I am looking into this workspace stuff now I used npm this whole time so will try and do with npm. Then I see all this new stuff turborepo and vercel this is all new to me but will try and get a workspace going or monorepo whatever it may be called. And tbh I never give too much thought into all this npm yarn npx nvm pnmp stuff always just use the old ball and chain npm
@josefaidt @ErikCH here is my attempt with workspaces. I think its correct but I'm still new to this https://github.com/24jr/test1 but when try and host I got
!!!Monorepo spec provided without "applications" key
I dont think hitting reconnect did anything so I just deleted that repo and added again. This is what doing lmk if something stands out
Which is what I did before and yields same error of course
Ok this might have to do with when I added yml it wasn't identified by amplify while in root project so I moved it to root. https://github.com/aws-amplify/amplify-console/issues/1995 https://docs.aws.amazon.com/amplify/latest/userguide/monorepo-configuration.html possibly just need to add applications and appRoot although yours doesn't seem to have that but I'll attempt this in a bit
Hey @24jr can you try unchecking the "connecting a monorepo?" field and removing the folder choice? In the buildspec file (amplify.yml
) listed in the above repository we're leveraging the baseDirectory
property to direct Amplify to look for build files in the monorepo's workspace directory instead. https://github.com/josefaidt/amplify-discord-bots/blob/main/amplify.yml#L14
@24jr I created a small repository to showcase the set up where we can follow the commits for steps, however you can amplify add hosting
at the last step to avoid multiple builds. It is important to note how we configure our project as well, pointing the src
directory to the packages/aws-exports
workspace (this is to tell the CLI where to generate the aws-exports.js
file) https://github.com/josefaidt/amplify-svelte-kit-workaround/commit/630a3f347f251ef23de373891524053575c16eee#diff-b52cd865940ad3e166cf4a0f7870d325da9ecb1264d52e1b1ffaf33da2754f86
repository: https://github.com/josefaidt/amplify-svelte-kit-workaround/commits/main live site: https://main.d1vfckhhiu71it.amplifyapp.com/

@josefaidt Ok I went through based on your guide except stuck with npm. And didnt select updated backend locally because usually failed but maybe doesnt with workspaces didnt try but rather went through amplify studio in same steps as before. I think adapter-auto is new that is default with the skeleton svelte proj which I notice puts the build file in the svelte-kit file while the adapter-static puts the build file in the app root.
I still failed at getting build latest I have is this which I think is all the steps but maybe skipped some. https://github.com/24jr/test2 is my latest. Here is latest build error and I will go to sleep now and try again tomorrow





I did mine all with npm workspaces. I still am going to need to figure out the ins and outs of some of this workspace stuff and get used to it but it seems like not too complicated and something I can get behind. Thanks again!
I also havent tried adding auth and graphQL stuff and what not just this base stuff but I think will work we will see
Ahhhh I'm glad to hear you're up and running with Svelte-Kit @24jr 🙌 ! A few notes:
-
nvm install 16
is installing Node 16, Console provides Node 12 by default - the new
adapter-auto
Svelte-Kit adapter replaces the need to specify adapters for platforms like Vercel, Netlify, and CloudFlare (reference: https://github.com/sveltejs/kit/blob/master/packages/adapter-auto/adapters.js), more on deploying static Svelte-Kit sites here https://kit.svelte.dev/docs#adapters-supported-environments-static-sites
That's also awesome to hear you were able to adapt this setup to use npm workspaces!
@josefaidt you changed my future lol. Thanks again. I changed the name of what I had and maybe I'll try and leave up as basis for me and others to go off of. Of course things change over time but good until then https://github.com/24jr/amplify-sveltekit-template I made some components and added auth to this as well @ErikCH
@josefaidt Do you know why this is giving me this error? Missing "./package.json" export in "aws-exports" package
perhaps something with this https://github.com/vitejs/vite/issues/1505 or https://github.com/vitejs/vite/issues/3417 or https://nodejs.org/api/packages.html#packages_subpath_patterns
might boil back down to this "type": "module" stuff again. They don't want us to succeed. I'm sure there are reasons for why so hard to get sveltekit working but hopefully just some different way to write this that works
{
"name": "aws-exports",
"exports": {
".": {
"import": "./aws-exports.js"
}
}
}



In my process of dipping my toe in the waters of nuxt this seems to be relevent to this issue and in fact has a similar silution to what we have i think so prob check this out https://v3.nuxtjs.org/concepts/esm
Hey @24jr my apologies, missed that part. We'll want to add the following:
{
"name": "aws-exports",
"exports": {
".": {
"import": "./aws-exports.js"
- }
+ },
+ "./package.json": "./package.json"
}
}
I have the exact same issue, and I am very glad you guys discussed this only a few days ago! I looked at both of your repos (first @24jr's, then @josefaidt's) and did my best to structure my existing code and do all the corresponding configuration. I now have this error in the build (cloning repository) step:
2021-12-20T09:53:41.570Z [INFO]: Successfully cleaned up Git credentials
2021-12-20T09:53:41.570Z [INFO]: # Checking for Git submodules at: /codebuild/output/src062215029/src/lightbulb-learning/.gitmodules
2021-12-20T09:53:41.593Z [INFO]: # Retrieving environment cache...
2021-12-20T09:53:41.623Z [INFO]: # Retrieved environment cache
2021-12-20T09:53:41.623Z [INFO]: ---- Setting Up SSM Secrets ----
2021-12-20T09:53:41.623Z [INFO]: SSM params {"Path":"/amplify/d2wcvgtmnc7koy/sveltekit-picocss/","WithDecryption":true}
2021-12-20T09:53:50.166Z [INFO]: # Patching NPM package '@aws-amplify/cli' from 4.29.4 to 7.6.4...
2021-12-20T09:54:23.948Z [INFO]: npm WARN deprecated @graphql-toolkit/[email protected]: GraphQL Toolkit is deprecated and merged into GraphQL Tools, so it will no longer get updates. Use GraphQL Tools instead to stay up-to-date! Check out https://www.graphql-tools.com/docs/migration-from-toolkit for migration and https://the-guild.dev/blog/graphql-tools-v6 for new changes.
2021-12-20T09:54:30.329Z [INFO]: npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated
2021-12-20T09:54:30.335Z [INFO]: npm WARN
2021-12-20T09:54:30.335Z [INFO]: deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated
2021-12-20T09:54:31.532Z [INFO]: npm WARN deprecated [email protected]: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
2021-12-20T09:54:35.275Z [INFO]: npm WARN deprecated
2021-12-20T09:54:35.276Z [INFO]: @graphql-toolkit/[email protected]: GraphQL Toolkit is deprecated and merged into GraphQL Tools, so it will no longer get updates. Use GraphQL Tools instead to stay up-to-date! Check out https://www.graphql-tools.com/docs/migration-from-toolkit for migration and https://the-guild.dev/blog/graphql-tools-v6 for new changes.
2021-12-20T09:54:35.953Z [INFO]: npm WARN deprecated [email protected]: GraphQL Import has been deprecated and merged into GraphQL Tools, so it will no longer get updates. Use GraphQL Tools instead to stay up-to-date! Check out https://www.graphql-tools.com/docs/migration-from-import for migration and https://the-guild.dev/blog/graphql-tools-v6 for new changes.
2021-12-20T09:54:50.332Z [INFO]: npm WARN
2021-12-20T09:54:50.338Z [INFO]: deprecated [email protected]: Use promise-toolbox/fromEvent instead
2021-12-20T09:55:52.028Z [INFO]: npm
2021-12-20T09:55:52.038Z [INFO]: WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.3.2 (node_modules/@aws-amplify/cli/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
2021-12-20T09:55:52.039Z [INFO]: npm WARN @aws-amplify/[email protected] requires a peer of react@^17.0.2 but none is installed. You must install peer dependencies yourself.
2021-12-20T09:55:52.043Z [INFO]: npm WARN @aws-amplify/[email protected] requires a peer of react-dom@^17.0.2 but none is installed. You must install peer dependencies yourself.
2021-12-20T09:55:52.044Z [INFO]:
2021-12-20T09:55:52.126Z [INFO]: # Done patching NPM package '@aws-amplify/cli' to version 7.6.4
2021-12-20T09:55:52.138Z [WARNING]: !TypeError: Cannot read property 'trim' of undefined
2021-12-20T09:55:52.139Z [ERROR]: !!! TypeError: Cannot read property 'trim' of undefined
2021-12-20T09:55:52.139Z [INFO]: # Starting environment caching...
2021-12-20T09:55:52.140Z [INFO]: # Environment caching completed
Terminating logging...
This doesn't happen when building locally. You can see my whole code in my repo here. Do you have anything in mind that I should check to get this running?
@Robert-Nickel I may have had that problem and found that some of my imports had different capitalization than was accurate and locally was fine but failed like this in build. Like may have '$lib/Components/Button/index.svelte'
instead import Button from '$lib/components/Button/index.svelte'
but could be something different here
Hey @24jr!
Wow, the repo is awesome! Thanks for putting that together. Also thanks for @josefaidt for all the help! I'll keep everyone updated with the progress on the amplify-ui library!
Hey @24jr and @josefaidt !
I just published a Proof-Of-Concept (POC) version of the authenticator with Svelte, using SvelteKit. Right now it only works with SignIn, but soon it will have more functionality! Feel free to check out the repo as well with any thoughts or comments
To get it running follow these steps
$ npm init svelte@next your-demo
$ cd your-demo
$ yarn add aws-amplify @aws-amplify/ui-svelte@next
Update these files
App.html
...
<script>
window.global = window;
var exports = {};
</script>
svelte.config.js (working on reducing deps now)
import adapter from '@sveltejs/adapter-static';
import preprocess from 'svelte-preprocess';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: preprocess(),
kit: {
adapter: adapter(),
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte',
vite: {
optimizeDeps: {
include: [
'lodash',
'lodash/merge',
'lodash/isEmpty',
'lodash/includes',
'lodash/kebabCase',
'xstate/lib/actions',
'lodash/pickBy',
'lodash/get',
'style-dictionary/lib/utils/deepExtend',
'style-dictionary/lib/utils/flattenProperties',
'style-dictionary/lib/utils/references/usesReference'
]
},
plugins: [],
ssr: {
noExternal:
process.env.NODE_ENV !== 'development' ? ['lodash', 'xstate', 'style-dictionary'] : []
},
resolve: {
alias: {
'./runtimeConfig': './runtimeConfig.browser'
}
}
}
}
};
export default config;
Then just add the Authenticator to your routes.
index.svelte
<script lang="ts">
import { Amplify } from 'aws-amplify';
import { Authenticator, authStore } from '@aws-amplify/ui-svelte';
import '@aws-amplify/ui-svelte/styles.css';
Amplify.configure({ });
const { signOut, user } = authStore;
</script>
<Authenticator>
<h1>Hello {$user.username}!</h1>
<button on:click={signOut}>Sign Out</button>
</Authenticator>
Let me know!
@ErikCH @josefaidt Is there a diff between app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="" />
<link rel="icon" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%svelte.head%
<script>
// temporary workaround for Amplify JS
window.global = window;
var exports = {};
</script>
</head>
</head>
<body>
<div id="svelte">%svelte.body%</div>
</body>
</html>
and
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="" />
<link rel="icon" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%svelte.head%
</head>
<body>
<div id="svelte">%svelte.body%</div>
</body>
</html>
<script>
const isBrowser = () => typeof window !== 'undefined';
const isGlobal = () => typeof global !== 'undefined';
var exports = {};
if (!isGlobal() && isBrowser()) {
var global = window;
}
</script>
I prev had longer one until noticed josef had shorter one and that seemed to work fine.
I just tested this and sign in worked for me. I did not use workspaces or build for hosting but maybe the new config file here is for solving stuff like that. I also tried half signing in on my other site and having it send email code but not verifying and on sign in got error that didnt show I believe
Hey @24jr !
Yes you are right, the shorter app.html
will work. I just copied and pasted yours, thinking you saw something I didn't! I'll update the post.
I have not tried hosting, but it should work the same. The new svelte config is mostly because we are using xstate
, lodash
and style-dictionary
in our @aws-amplify/ui
library. Xstate is our internal store, that we share between all the different implementations of the authenticator
. style-dictionary
is mostly for our theming, which one day we could see bringing to other frameworks, other then React. I'd like to remove lodash
in the future. Or maybe switch to lodash-es
which is more ESM friendly.
I don't have any verification built in yet, if that's the test you were running. My next step is to get sign-up working. Thanks for taking a look.
@ErikCH ok perfect yeah i didnt think through the logic of what any of that is doing just copied from solution to issue a while back and worked but i think I did switch to shorter one in the template I made because I always choose shorter lol but idk if. there was reason for other way. The reason I had to use workspaces was because that was the only way it worked for hosting before (solution found thanks to @josefaidt )
@ErikCH thank you for your work with this! Will the svelte-ui repo work with all of amplify, or just Auth?