SlideShare a Scribd company logo
Authentication in
Svelte using cookies
Alka Vats & Anuj Tomar
Lack of etiquette and manners is a huge turn off.
KnolX Etiquettes
 Punctuality
Join the session 5 minutes prior to the session start time. We start on
time and conclude on time!
 Feedback
Make sure to submit a constructive feedback for all sessions as it is very
helpful for the presenter.
 Silent Mode
Keep your mobile devices in silent mode, feel free to move out of session
in case you need to attend an urgent call.
 Avoid Disturbance
Avoid unwanted chit chat during the session.
1. Introduction to SvelteKit
2. What are HTTP cookies?
3. Understanding SvelteKit cookies methods
4. Authentication using the parent() function
5. Implementing authentication with SvelteKit
o Build the UI
o Authentication endpoints
o Svelte hooks
6. Securing routes and accessing the session on
the client
Introduction to SvelteKit
Introduction to SvelteKit
 SvelteKit is to Svelte what Next.js is to React.
 SvelteKit is a framework for building web applications of all sizes, with a beautiful
development experience and flexible file system–based routing.
 SvelteKit extends Svelte with some functionality that we will use in this knolx session:
− file system–based routing
− endpoints (server-side functions)
− hooks.
02
What are HTTP cookies?
 Cookies, also known as HTTP cookies, are small text files that websites store on a
user’s computer or mobile device.
 These files contain data related to the user’s browsing activity on that website, such as
login information, preferences, and shopping cart contents.
 Cookies can be either “session cookies” or “persistent cookies.”
 Session cookies are temporary and deleted when the user closes their browser, while
persistent cookies remain on the user’s device until they expire or are deleted by the
user.
Cookies in SvelteKit
• SvelteKit’s cookies have a new method for a cookie
header, and also removed the getSession property,
which returns the data that was set in user session.
• With this new concept, it’s now much easier to work
with cookies compared to adding payload manually to
the request header.
• This update comes with a set of flexible methods,
including set, get, and delete.
 Session management
 Persistence
 Client-side storage
 Cross-domain compatibility
 Scalability
Advantages of using cookies:
Disadvantages of using cookies
 Security concerns:
- Care must be taken to properly sanitize input and validate data to prevent these
types of security attacks
 Size limitations:
- Cookies have a size limit of around 4KB, which may not be sufficient for storing
larger amounts of data. This can limit the amount of data that can be stored on the
client side
 Compatibility issues:
- Some users may have cookies disabled or may be using older browsers that do not
support cookies. This can limit the effectiveness of using cookies as a data storage
mechanism
03
The 'set' method
 This method is used to set cookies in the Set-Cookie header and define options as needed, making the cookies available
for recurring usage.
 To use the set method, you need to provide name , value, and option — option is optional. These config options allow us to
specify various options that help ensure security and restriction to the cookie data:
cookies.set('sessionId', "info@gmail.com", {
httpOnly: true,
sameSite: 'strict',
secure: false,
path: '/',
maxAge: 60 * 60 * 24 * 7
});
The 'get' method
 This method is used to get cookie data that was previously set with cookies.set, or from the request headers.
 The get method takes two parameters: name and options, though options is optional:
cookies.get('session');
 This method is used to delete a cookie from the browser.
 Deleting a cookie removes the data and the expiry period attached to that cookie.
 This method takes two parameters: name and options; again, options is optional:
await cookies.delete('session', {path: '/'});
The 'delete' method
04
Authentication using the parent() function
 The parent() function is used to return props data from various load functions, then combine them together as one object.
 Additionally, the load function is used to return data from the server/client to the Svelte template:
//src/routes/+layout.server.js
export const load = async ({ request, locals, cookies }) => {
return {
user: locals.user,
welcome_message: "welcome back",
}; };
 The +page.js is executed on the client side while the other files with .server.js are executed on the backend:
//src/routes/+page.js
export const load = async ({ parent }) => {
const { user, welcome_message } = await parent();
return {
user: user,
message: welcome_message
};};
05
Implementing authentication with SvelteKit
- Setup
First, we’ll initialize the SvelteKit project.
npm create svelte@latest sveltekit-auth
cd sveltekit-auth
npm install
Authentication endpoints/workflow
 First, we need one additional library that will help us generate a random ID for each user:
npm i uuid
Svelte hooks
 Svelte hooks run on the server and allow us to extend the behavior of SvelteKit.
 The handle hook runs on every request (and during prerendering).
 It gives us access to the request and allows us to modify the response.
 We can add custom data to request.locals, which will be available in all endpoints.
 We will use it to parse the session_id cookie, retrieve the session, and attach the session
data to request.locals.
 The hook, which can also be referred to as a middleware, helps us handle the unauthorized
user trying to access protected pages.
06
Securing routes and accessing the session
on the client
 In /src/routes/protected, we can create another route, called /protected that will only be
accessible by authenticated users.
 We can then check if the session contains the user. If that’s not the case, the user isn’t signed
in.
 We can redirect the user by returning the combination of HTTP status code 302 (found) and
a redirect pointing to the route where the user should be redirected.
 Because the load function is running before the actual rendering of the page, an
unauthenticated user will never see the page.
Securing routes and accessing the session
on the client
 This is how the protected route looks:
// src/routes/protected/+page.svelte
<script>
export let data;
</script>
<svelte:head>
<title>Protected Page</title>
<meta name="description" content="About this app" />
</svelte:head>
<h1 class="text-2xl font-semibold text-center">Hi! You are registered with email: {data.user.email}.</h1>
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx

More Related Content

Authentication in Svelte using cookies.pptx

  • 1. Authentication in Svelte using cookies Alka Vats & Anuj Tomar
  • 2. Lack of etiquette and manners is a huge turn off. KnolX Etiquettes  Punctuality Join the session 5 minutes prior to the session start time. We start on time and conclude on time!  Feedback Make sure to submit a constructive feedback for all sessions as it is very helpful for the presenter.  Silent Mode Keep your mobile devices in silent mode, feel free to move out of session in case you need to attend an urgent call.  Avoid Disturbance Avoid unwanted chit chat during the session.
  • 3. 1. Introduction to SvelteKit 2. What are HTTP cookies? 3. Understanding SvelteKit cookies methods 4. Authentication using the parent() function 5. Implementing authentication with SvelteKit o Build the UI o Authentication endpoints o Svelte hooks 6. Securing routes and accessing the session on the client
  • 5. Introduction to SvelteKit  SvelteKit is to Svelte what Next.js is to React.  SvelteKit is a framework for building web applications of all sizes, with a beautiful development experience and flexible file system–based routing.  SvelteKit extends Svelte with some functionality that we will use in this knolx session: − file system–based routing − endpoints (server-side functions) − hooks.
  • 6. 02
  • 7. What are HTTP cookies?  Cookies, also known as HTTP cookies, are small text files that websites store on a user’s computer or mobile device.  These files contain data related to the user’s browsing activity on that website, such as login information, preferences, and shopping cart contents.  Cookies can be either “session cookies” or “persistent cookies.”  Session cookies are temporary and deleted when the user closes their browser, while persistent cookies remain on the user’s device until they expire or are deleted by the user.
  • 8. Cookies in SvelteKit • SvelteKit’s cookies have a new method for a cookie header, and also removed the getSession property, which returns the data that was set in user session. • With this new concept, it’s now much easier to work with cookies compared to adding payload manually to the request header. • This update comes with a set of flexible methods, including set, get, and delete.  Session management  Persistence  Client-side storage  Cross-domain compatibility  Scalability Advantages of using cookies:
  • 9. Disadvantages of using cookies  Security concerns: - Care must be taken to properly sanitize input and validate data to prevent these types of security attacks  Size limitations: - Cookies have a size limit of around 4KB, which may not be sufficient for storing larger amounts of data. This can limit the amount of data that can be stored on the client side  Compatibility issues: - Some users may have cookies disabled or may be using older browsers that do not support cookies. This can limit the effectiveness of using cookies as a data storage mechanism
  • 10. 03
  • 11. The 'set' method  This method is used to set cookies in the Set-Cookie header and define options as needed, making the cookies available for recurring usage.  To use the set method, you need to provide name , value, and option — option is optional. These config options allow us to specify various options that help ensure security and restriction to the cookie data: cookies.set('sessionId', "info@gmail.com", { httpOnly: true, sameSite: 'strict', secure: false, path: '/', maxAge: 60 * 60 * 24 * 7 });
  • 12. The 'get' method  This method is used to get cookie data that was previously set with cookies.set, or from the request headers.  The get method takes two parameters: name and options, though options is optional: cookies.get('session');  This method is used to delete a cookie from the browser.  Deleting a cookie removes the data and the expiry period attached to that cookie.  This method takes two parameters: name and options; again, options is optional: await cookies.delete('session', {path: '/'}); The 'delete' method
  • 13. 04
  • 14. Authentication using the parent() function  The parent() function is used to return props data from various load functions, then combine them together as one object.  Additionally, the load function is used to return data from the server/client to the Svelte template: //src/routes/+layout.server.js export const load = async ({ request, locals, cookies }) => { return { user: locals.user, welcome_message: "welcome back", }; };  The +page.js is executed on the client side while the other files with .server.js are executed on the backend: //src/routes/+page.js export const load = async ({ parent }) => { const { user, welcome_message } = await parent(); return { user: user, message: welcome_message };};
  • 15. 05
  • 16. Implementing authentication with SvelteKit - Setup First, we’ll initialize the SvelteKit project. npm create svelte@latest sveltekit-auth cd sveltekit-auth npm install Authentication endpoints/workflow  First, we need one additional library that will help us generate a random ID for each user: npm i uuid
  • 17. Svelte hooks  Svelte hooks run on the server and allow us to extend the behavior of SvelteKit.  The handle hook runs on every request (and during prerendering).  It gives us access to the request and allows us to modify the response.  We can add custom data to request.locals, which will be available in all endpoints.  We will use it to parse the session_id cookie, retrieve the session, and attach the session data to request.locals.  The hook, which can also be referred to as a middleware, helps us handle the unauthorized user trying to access protected pages.
  • 18. 06
  • 19. Securing routes and accessing the session on the client  In /src/routes/protected, we can create another route, called /protected that will only be accessible by authenticated users.  We can then check if the session contains the user. If that’s not the case, the user isn’t signed in.  We can redirect the user by returning the combination of HTTP status code 302 (found) and a redirect pointing to the route where the user should be redirected.  Because the load function is running before the actual rendering of the page, an unauthenticated user will never see the page.
  • 20. Securing routes and accessing the session on the client  This is how the protected route looks: // src/routes/protected/+page.svelte <script> export let data; </script> <svelte:head> <title>Protected Page</title> <meta name="description" content="About this app" /> </svelte:head> <h1 class="text-2xl font-semibold text-center">Hi! You are registered with email: {data.user.email}.</h1>