GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - svelte-dev/session: Simple Session Storage Management for Svelte

BranchesTags
Open more actions menu
 
 

Latest commit

 

History

21 Commits
21 Commits

Folders and files

NameName
Last commit message
Last commit date
.github
.github
 
 
.husky
.husky
 
 
.vscode
.vscode
 
 
src
src
 
 
static
static
 
 
test
test
 
 
.codeclimate.yml
.codeclimate.yml
 
 
.commitlintrc.cjs
.commitlintrc.cjs
 
 
.editorconfig
.editorconfig
 
 
.eslintignore
.eslintignore
 
 
.eslintrc.cjs
.eslintrc.cjs
 
 
.gitignore
.gitignore
 
 
.npmrc
.npmrc
 
 
.prettierignore
.prettierignore
 
 
.prettierrc
.prettierrc
 
 
CHANGELOG.md
CHANGELOG.md
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
bun.lockb
bun.lockb
 
 
package.json
package.json
 
 
svelte.config.js
svelte.config.js
 
 
tsconfig.json
tsconfig.json
 
 
tsconfig.typedoc.json
tsconfig.typedoc.json
 
 
typedoc.json
typedoc.json
 
 
vite.config.ts
vite.config.ts
 
 
wrangler.toml
wrangler.toml
 
 

Repository files navigation

@svelte-dev/session

github npm npm npm Maintainability Test Coverage

Simple Session Storage Management for Svlelte.

  • Overview
  • Installation
  • Usage
  • Advanced Usage
    • Session API
    • Cloudflare KV
    • Custom Handler
    • Typescript
    • Create your own stragety
  • 赞助 Sponsor
  • 许可证 License

Overview

Sessions are an important part of websites that allow the server to identify requests coming from the same person, especially when it comes to server-side form validation or when JavaScript is not on the page. Sessions are a fundamental building block of many sites that let users "log in", including social, e-commerce, business, and educational websites.

Svelte-Session comes with several pre-built session storage options for common scenarios, and one to create your own:

  • custom storage with createCustomStrategy
  • CookieSessionStrategy
  • MemoryStrategy
  • CloudflareKVStrategy (Cloudflare Workers)

Installation

To use it, install it from npm (yarn or bun):

npm install @svelte-dev/session

Usage

Init from hooks.server.ts:

import { handleSession } from '@svelte-dev/session';

export const handle = handleSession({
  adapter: {
    name: 'cookie',
    options: {
      chunk: true
    }
  },
  session: {
    key: '__sid',
    secrets: ['s3cr3t']
  },
  cookie: {
    path: '/',
    sameSite: 'lax',
    secure: true,
    httpOnly: true
  }
});

Load Data from +page.server.ts:

import type { ServerLoad } from '@sveltejs/kit';

export const load: ServerLoad = async ({ locals }) => {
  const views = locals.session.get('views') ?? 0;
  await locals.session.set('views', views + 1);
  return {};
};

Use in svelte5 runes component:

<script>
  let { data } = $props();
</script>

<pre>
  {JSON.stringify(data, null, 2)}
</pre>

Advanced Usage

Session API

See: https://svelte-session.js.cool/ For more details

Cloudflare KV

Init from hooks.server.ts:

import { handleSession } from '@svelte-dev/session';

export const handle = handleSession({
  adapter: {
    name: 'cloudflare-kv',
    options: {
      namespace: 'SESSION'
    }
  },
  session: {
    secrets: ['s3cr3t']
  },
  cookie: {
    path: '/'
  }
});

Checkout the docs for more details: https://kit.svelte.dev/docs/adapter-cloudflare#bindings

Custom Handler

export const handle = handleSession({
		adapter: {
		name: 'cookie',
		options: {
			chunk: true
		}
	},
	session: {
		key: '__sid',
		secrets: ['s3cr3t']
	},
	cookie: {
		path: '/',
		sameSite: 'lax',
		secure: true,
		httpOnly: true
	},
	({ event, resolve }) => {
		// event.locals is populated with the session `event.locals.session`
		// Do anything you want here
		return resolve(event);
	}
);

In case you're using sequence(), do this

const sessionHandler = handleSession({
  adapter: {
    name: 'cookie',
    options: {
      chunk: true
    }
  }
});

export const handle = sequence(sessionHandler, ({ resolve, event }) => {
  // event.locals is populated with the session `event.locals.session`
  // event.locals is also populated with all parsed cookies by handleSession, it would cause overhead to parse them again - `event.locals.cookies`.
  // Do anything you want here
  return resolve(event);
});

Typescript

Here's a simple example, modify app.d.ts:

import type { FlashSessionData, SessionData, SessionStorage } from '@svelte-dev/session';

declare global {
  namespace App {
    // interface Error {}
    interface Locals {
      session: SessionStorage<{ views: number }>;
    }
    interface PageData {
      session: FlashSessionData<SessionData, SessionData>;
    }
    interface Session extends SessionStorage {}
    // interface Platform {}
  }
}

Create your own stragety

import type { RequestEvent } from '@sveltejs/kit';
import type {
  CookieOptions,
  FlashSessionData,
  SessionData,
  SessionOptions,
  SessionStorageStrategy
} from '@svelte-dev/session';

export type YourStrageOptions = {
  /**
   * Example
   */
  key?: string;
};

export class YourStrategy<Data = SessionData, FlashData = Data>
  implements SessionStorageStrategy<Data, FlashData>
{
  constructor(
    event: RequestEvent,
    options: YourStrageOptions & { cookie: CookieOptions; session: SessionOptions }
  ) {}
  /**
   * Creates a new record with the given data and returns the session id.
   */
  async createData(data, expires?: Date): Promise<string> {}

  /**
   * Returns data for a given session id, or `null` if there isn't any.
   */
  async readData(id: string): Promise<FlashSessionData<Data, FlashData> | null> {}

  /**
   * Updates data for the given session id.
   */
  async updateData(
    id: string,
    data: FlashSessionData<Data, FlashData>,
    expires?: Date
  ): Promise<void> {}

  /**
   * Deletes data for a given session id from the data store.
   */
  async deleteData(id: string): Promise<void> {}
}

赞助 Sponsor

维护者 Owner: Willin Wang

如果您对本项目感兴趣,可以通过以下方式支持我:

  • 关注我的 Github 账号:@willin github
  • 参与 爱发电 计划
  • 支付宝或微信扫码打赏

Donation ways:

  • Github: https://github.com/sponsors/willin
  • Paypal: https://paypal.me/willinwang
  • Alipay or Wechat Pay: QRCode

许可证 License

Apache-2.0

About

Simple Session Storage Management for Svelte

svelte-session.js.cool/

Resources

Readme
License

Code of conduct

Code of conduct

Contributing

Contributing
Activity
Custom properties

Stars

1 star

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.