Logo Blog Newsletters

Configure Amplify Authentication With SvelteKit

Published on October 3, 2023
~ 3 min read
Amplify
SvelteKit
Cognito
AWS
Svelte
Article cover

Installing SvelteKit

First we need to install SvelteKit, we can work with the default example.

    npm create svelte@latest sveltekit-amplify
    Need to install the following packages:
        create-svelte@2.3.0
    Ok to proceed? (y)

    create-svelte version 2.3.0

    Welcome to SvelteKit!
    √ Which Svelte app template? » SvelteKit demo app
    √ Add type checking with TypeScript? » Yes, using TypeScript syntax
    √ Add ESLint for code linting? ... Yes
    √ Add Prettier for code formatting? ... Yes
    √ Add Playwright for browser testing? ... No
    √ Add Vitest for unit testing? ... No

Then we run

    npm install 
    npm install aws-amplify

Perfect everything is installed, let's use Amplify.

AWS Exports

I won't install Amplify using its CLI because we really just need to add a file and a few lines within the project.

So we need to create a file called aws-exports.ts within src/ folder. You can copy and then customize this configuration πŸ‘‡

    /* eslint-disable */
    // WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

    const awsmobile = {
            "aws_project_region": "$REGION",
            "aws_cognito_region": "$REGION",
            "aws_user_pools_id": "$USER_POOL_ID",
        "aws_user_pools_web_client_id": "$USER_POOL_CLIENT_ID",
            "oauth": {
                "domain": "$USER_POOL_DOMAIN.auth.$REGION.amazoncognito.com"
            },
            "aws_cognito_username_attributes": [
                    "EMAIL"
            ],
            "aws_cognito_social_providers": [],
            "aws_cognito_signup_attributes": [],
            "aws_cognito_mfa_configuration": "OFF",
            "aws_cognito_mfa_types": [],
            "aws_cognito_password_protection_settings": {
                    "passwordPolicyMinLength": 10,
                    "passwordPolicyCharacters": [
                            "REQUIRES_LOWERCASE",
                            "REQUIRES_UPPERCASE",
                            "REQUIRES_NUMBERS",
                            "REQUIRES_SYMBOLS"
                    ]
            },
            "aws_cognito_verification_mechanisms": [
                    "EMAIL",
                    "PHONE_NUMBER"
            ],
    };


    export default awsmobile;

Amplify configure

Next step is adding Amplify configuration, to do it we need to change the file src/routes/+layout.ts and add this snippet as script πŸ‘‡

    import { Amplify } from 'aws-amplify';
    import awsmobile from '../aws-exports';
    Amplify.configure(awsmobile);

Importing Amplify auth

Then we need to import Auth amplify aws-amplify within the file src/routes/login/+page.svelte like so πŸ‘‡

    <script lang="ts">
        import { Auth } from 'aws-amplify';
        ...
    </script>

An voilà: ReferenceError: global is not defined ⚠️

How to fix "ReferenceError: global is not defined"?

We need to define a simple script to src/app.html πŸ‘‡

        ...
        <script>
            if (global === undefined) {
                var global = window;
            }
        </script>
        ...

Perfect, let's write a simple page just to try out, we would use this function to signIn (or signUp whatever you prefer)

    await Auth.signIn(username, password);

And finally we can signIn successfully this time! πŸŽ‰πŸŽ‰

Cognito response after sign inSvelteKit build

SvelteKit build

Finally let's try to build the project by executing vite build and…. "request" is not exported by "__vite-browser-external", imported by "node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js".

How to fix "request" is not exported by "__vite-browser-external"?

We need to change vite configuration file named vite.config.ts like this πŸ‘‡

    import { sveltekit } from '@sveltejs/kit/vite';
    import type { UserConfig } from 'vite';

    const config: UserConfig = {
        plugins: [sveltekit()],
        resolve: {
            alias: {
                './runtimeConfig': './runtimeConfig.browser',
            }
        }
    };

    export default config;

Then hit vite build once again and… WE DID ITπŸΎπŸŽ‰

Conclusion

In this posts we learnt how to configure Amplify Auth with SvelteKit, doing so we are able to integrate the authentication with Amazon Cognito without spilling too much blood 😜.

You can find the project here https://github.com/Depaa/amplify-sveltekit πŸ˜‰

Follow this journey to production, you will see a lot of blog posts, here is a list I'll try to keep updated:

  • βœ… Serverless infrastructure on AWS for blog website;
  • βœ… Backend Api on AWS for blog website;
  • βœ… Building a high performing static backoffice on AWS with SvelteKit;
  • βœ… Frontend users website for reading blog posts;
  • βœ… SEO tweaks for blog website;
  • βœ… Analytics and tracking views on our blog website;
  • Infrastructure monitoring and alerting to the blog;
  • Going live with the blog;
  • CICD pipelines for the blog;
  • Disaster recovery, RTO and RPO. Going multiregion with serverless;
  • … you see, there are a lot planned, and if you want to add more points just DM me or comment right below.

Thank you so much for reading! πŸ™ I will keep posting different AWS architecture from time to time so follow me on LinkedIn πŸ‘‰ https://www.linkedin.com/in/matteo-depascale/.