@ethercorps/sveltekit-redis-session
v1.3.1
Published
A library which uses svelte compiler to convert html & css to jsx. Useful for using satori with svelte & Kit
Downloads
1,470
Maintainers
Readme
About The Project
"SvelteKit-Redis-Session" stands out as an indispensable tool for developers aiming to seamlessly integrate Redis as a session manager within their SvelteKit applications. Designed with a keen attention to detail, this package ensures that managing user sessions is not only efficient but also intuitive.
Key Features
Simplicity at its Core
: With intuitive functions, developers can effortlessly store and retrieve data without wading through complexities.Enhanced Security
: Understanding the need for robust data protection, the package offers signature & encryption for session data.Intelligent Session Management
: The package intelligently handles session expiration, reducing the manual oversight typically needed.Bespoke Customization
: Recognizing that one size doesn't fit all, "SvelteKit-Redis-Session" offers high customizability, allowing developers to tailor its functionalities to their distinct needs, and in turn, enhancing application performance.For all runtimes
: As of now we have so many runtimes cloudflare workers, vercel, netlify.Support for multiple redis libraries
: We supportredis
&ioredis
out of the box.Support for @upstash/redis
: It's mandatory if you are working with workers, edge and serverless. Cloudflare workers doesn't support TCP.
Built With
Getting Started
This is an example of how you may give instructions on setting up your project locally. To get a local copy up and running follow these simple example steps.
Prerequisites
This is an example of how to list things you need to use the software and how to install them.
- Install the
@ethercorps/sveltekit-redis-session
pnpm i @ethercorps/sveltekit-redis-session
- Choose which redis library you are using:
redis
: Official redis nodeJs implementationpnpm i redis
ioredis
: A robust, performance-focused and full-featured Redis client for Node.js.pnpm i ioredis
@upstash/redis
: is an HTTP/REST based Redis client built on top of Upstash REST API.pnpm i @upstash/redis
Setup
First, we need to make instance of it to use everywhere in the project.
import { IoRedisSessionStore } from '@ethercorps/SvelteKit-redis-session'; import Redis from 'ioredis'; export const sessionManager = new IoRedisSessionStore({ redisClient: new Redis(), // Required A pre-initiated redis client secret: 'your-secret-key', // Required A secret key for encryption and other things, cookieName: 'session', // CookieName to be saved in cookies for browser Default session prefix: 'sk-session', // Prefix for Redis Keys Default sk-session signed: true, // Do you want to sign your cookies Default true encrypted: false, // Do you want to encrypt your cookies using 'aes-256-cbc' algorithm Default false useTTL: true, // Do you wanna use redis's Expire key functionality Default false renewSessionBeforeExpire: false, // Do you wanna update session expire time in built function Default false renewBeforeSeconds: 30 * 60, // If renewSessionBeforeExpire is true define your renew before time in seconds Default 30 minutes serializer: JSON, // You can define your own serializer functions to stringify and parse sessionData for redis Default JSON cookiesOptions: { path: '/', httpOnly: true, sameSite: 'strict', secure: !dev, // From SvelteKit "$app/environment" maxAge: 60 * 60 * 24 // You have to define time in seconds and it's also used for redis key expiry time } // You have more options these are default used in package for more check sveltekit CookieSerializeOptions type. });
These are the default config example you can use as per your need and make it better for your use. I have written an article to explain more about this package link for article.
To create a new session and add cookies for user after authentication
// Example it's a +page.server.ts import sessionManager from 'sessionManagerFile'; export const actions: Actions = { login: async ({ req, cookies, locals }) => { const formdata = await request.formData(); // Form validation && user validation const { data, error, message } = sessionManager.createSession(cookies, userData, userId); // data is the value we added to cookies, check for error which is a boolean and message. /* add data to locals too for accessing data from client */ throw redirect(307, '/dashboard'); } };
To get session data for the cookie
/* hooks.server.ts */ import sessionManager from 'sessionManagerFile'; export const handle: Handle = async ({ event, resolve }) => { /* your validation logic */ const { data, error, message } = sessionManager.getSession(event.cookies); // data is the User session data we saved to redis while login, check for error which is a boolean and message. /* do error check and then set data to locals as per your logic */ };
To update session expiry in redis and cookies
// in any server side file or endpoint where you can access browser cookies import sessionManager from 'sessionManagerFile'; const { data, error, message } = await sessionManager.updateSessionExpiry(cookies); // data is going to be null or key which is updated, error is a boolean value and message a string
To update session data in redis and cookies
// in any server side file or endpoint where you can access browser cookies import sessionManager from 'sessionManagerFile'; const { data, error, message } = await sessionManager.updateSession(cookies, newSessionData); // data is going to be null or key which is updated, error is a boolean value and message a string
To delete session from redis and cookie from browser
// Example it's a +page.server.ts import sessionManager from 'sessionManagerFile'; export const actions: Actions = { logout: async ({ cookies, locals }) => { const { data, error, message } = await sessionManager.deleteSession(cookies); // data is the value we deleted key, check for error which is a boolean and message. /* clear your locals too */ throw redirect(307, '/login'); } };
To get all sessions of a user from redis and cookie from browser
// Example it's a +server.ts import sessionManager from 'sessionManagerFile'; export const GET: RequestHandler = async ({ cookies, locals }) => { const { data, error, message } = await sessionManager.getSessionsByUserId(userId); // data is the session data array, check for error which is a boolean and message. /* clear your locals too */ return json({data}) } };
Usage
Examples are going to be added soon.
For more examples, please refer to the Examples
Roadmap
See the open issues for a full list of proposed features (and known issues).
License
Distributed under the MIT License. See LICENSE.txt
for more information.
Contact
Your Name - @theether0 - [email protected]
Project Link: https://github.com/etherCorps/SK-Redis-SessionManager
Acknowledgments
- logos-by-larkef from landingfolio :: For logo
- connect-redis by TJ Holowaychuk :: Creator of connect redis for express session.