AWS Amplify Auth (Cognito) + Sveltekit
I was building my app Sveltekit app with SST (backend) . When it came down to the frontend or say integration with the Sveltekit my…
I was building my app Sveltekit app with SST (backend) . When it came down to the frontend or say integration with the Sveltekit my options were to use
AWS Cognito Hosted ui
AWS SDK
AWS AMPLIFY
I wanted some control over my app with ease of use so i chose AMPLIFY
STEPS TO FOLLOW
// +layout.ts
//Setup the Amplify with the Config
import { Amplify } from "aws-amplify";
import { amplifyConfig } from "$lib/amplifyConfig";
Amplify.configure({...amplifyConfig ,ssr:true})Make sure you have the config in place with proper name
This will throw you an global is not defined error when run directly , atleast thats what i encountered , the fix was
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
<script>
var global = global || window
var Buffer = Buffer || []
var process = process || { env: { DEBUG: undefined }, version: [] }
</script>
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>Add that script to your app.html
//+page.svelte
<script lang="ts">
import { Auth } from 'aws-amplify';
const signIn = async () =>
await Auth.federatedSignIn({
customProvider: 'Google'
});
// Logout the authenticated user
const signOut = async () => await Auth.signOut();
</script>
<button on:click={signIn}>login</button>
<button on:click={signOut}>logout</button>CSR
We wrap the Auth with a store, you can skip it if you want . You can also do this directly , but i like to use stores as they improve the readability of the code
//lib/stores.ts
import { writable } from 'svelte/store';
import { Auth } from 'aws-amplify';
export function userStore() {
if (!globalThis.window) {
console.warn('Auth is not initialized on not in browser');
const { subscribe } = writable<any>(null);
return {
subscribe
};
}
const { subscribe, set } = writable<any>(null);
try {
Auth.currentUserInfo().then((value) => {
set(value);
});
} catch (error) {
console.log(error);
}
return {
subscribe
};
}// +page.svelte for /csr
<script lang="ts">
import { userStore } from '$lib/stores';
let user = userStore();
$: console.log($user);
</script>
{#if $user}
<p>{$user.attributes.given_name ?? ''} {$user.attributes.family_name ?? ''}</p>
<img src={$user.attributes.picture} alt="" />
{:else}
<p>Not Logged In</p>
{/if}SSR
// +page.server.ts -> /ssr
import { withSSRContext } from 'aws-amplify';
import type { PageServerLoad } from './$types';
import type { Context } from 'vm';
import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ cookies }) => {
try {
const req: Context = {
headers: {
cookie: cookies
.getAll()
.map((e) => `${e.name}=${e.value};`)
.join(' ')
}
};
const ssr = withSSRContext({ req });
const user = await ssr.Auth.currentUserInfo();
console.log(user);
if (user) {
return {
user
};
}
throw error(401, 'not authenticated');
} catch (err) {
throw error(401, 'not authenticated');
}
};// +page.svelte -> /ssr
<script lang="ts">
import type { PageServerData } from "./$types";
export let data:PageServerData
console.log(data);
let user:any =data.user
</script>
{#if user}
<p>{user.attributes.given_name ?? ''} {user.attributes.family_name ?? ''}</p>
<img src={user.attributes.picture} alt="" />
{:else}
<p>Not Logged In</p>
{/if}This is a simple working example for Amplify + Sveltekit
For backend Refer this
Comments ()