{"id":25866290,"url":"https://github.com/maxiviper117/example-asynclocalstorage-sveltekit","last_synced_at":"2026-06-08T03:32:26.818Z","repository":{"id":278733150,"uuid":"936597372","full_name":"Maxiviper117/example-AsyncLocalStorage-sveltekit","owner":"Maxiviper117","description":null,"archived":false,"fork":false,"pushed_at":"2025-03-16T12:45:17.000Z","size":40,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-16T13:35:08.534Z","etag":null,"topics":["asynclocalstorage","example","sveltekit"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Maxiviper117.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-02-21T11:05:19.000Z","updated_at":"2025-03-16T12:45:21.000Z","dependencies_parsed_at":"2025-02-21T12:22:38.525Z","dependency_job_id":"8c93ca60-4b68-4800-b23b-43f559b7051c","html_url":"https://github.com/Maxiviper117/example-AsyncLocalStorage-sveltekit","commit_stats":null,"previous_names":["maxiviper117/example-asynclocalstorage-sveltekit"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Maxiviper117/example-AsyncLocalStorage-sveltekit","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maxiviper117%2Fexample-AsyncLocalStorage-sveltekit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maxiviper117%2Fexample-AsyncLocalStorage-sveltekit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maxiviper117%2Fexample-AsyncLocalStorage-sveltekit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maxiviper117%2Fexample-AsyncLocalStorage-sveltekit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Maxiviper117","download_url":"https://codeload.github.com/Maxiviper117/example-AsyncLocalStorage-sveltekit/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maxiviper117%2Fexample-AsyncLocalStorage-sveltekit/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34047266,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-08T02:00:07.615Z","response_time":111,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asynclocalstorage","example","sveltekit"],"created_at":"2025-03-02T02:29:26.339Z","updated_at":"2026-06-08T03:32:26.813Z","avatar_url":"https://github.com/Maxiviper117.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# example-AsyncLocalStorage-sveltekit\n\nThis project demonstrates how to use Node.js' AsyncLocalStorage within a SvelteKit application to manage per-request data without the need for passing data manually through each load function.\n\n## Overview\n\nIn this example, the AsyncLocalStorage is initialized in the server hooks and is used to store the authenticated user and other request-specific data.\n\n## How AsyncLocalStorage Works\n\nAsyncLocalStorage provides a way to store data throughout the lifetime of an asynchronous operation. It allows you to create a storage context that is unique to each asynchronous execution chain. This is particularly useful in web applications where you need to maintain request-specific data across various asynchronous operations without explicitly passing it around.\n\n### Key Concepts\n\n1. **Context Creation**: A new context is created at the beginning of each request using `asyncLocalStorage.run()`. This context is a Map object that can store key-value pairs.\n\n2. **Setting Data**: Data can be stored in the context using the `setRequestData` function. This function retrieves the current context and sets the specified key-value pair.\n\n3. **Getting Data**: Data can be retrieved from the context using the `getRequestData` function. This function retrieves the current context and gets the value associated with the specified key.\n\n## Advantages Over event.locals and Load Function Waterfalls\n\n1. **Simplified Data Propagation**: With AsyncLocalStorage, data such as the authenticated user is set once during the request lifecycle and then accessed anywhere within that lifecycle, eliminating the need to manually pass values through `event.locals` in each load function.\n\n2. **Avoiding Load Function Waterfalls**: Instead of using `await parent()` in nested load functions, which can lead to complex chaining of asynchronous calls, AsyncLocalStorage allows direct access to the context data, thereby reducing boilerplate code.\n\n3. **Centralized Context Management**: Managing request-specific data with AsyncLocalStorage centralizes the data access layer. This not only simplifies the code by avoiding repetitive data passing but also minimizes potential errors in distributed data flow.\n\n## Code Snippets\n\n### 1. Initialization in hooks\n\nThe following snippet shows how the context is created and used in the `handle` hook to store the authenticated user:\n\n```typescript\n// src/hooks.server.ts\nimport { getUserFromToken } from '$lib/server/auth';\nimport { runWithContext, setRequestData } from '$lib/server/requestContext';\n\nexport const handle = async ({ event, resolve }) =\u003e {\n\treturn runWithContext(async () =\u003e {\n\t\tconst token = event.cookies.get('auth_token');\n\n\t\tif (token) {\n\t\t\tconst user = await getUserFromToken(token);\n\t\t\tsetRequestData('user', user);\n\t\t} else {\n\t\t\tconsole.warn('No valid auth token found');\n\t\t\tsetRequestData('user', null);\n\t\t}\n\n\t\treturn await resolve(event);\n\t});\n};\n```\n\n### 2. Context Management with AsyncLocalStorage\n\nThis snippet from `src/lib/server/requestContext.ts` demonstrates how AsyncLocalStorage is used to maintain a per-request store:\n\n```typescript\n// src/lib/server/requestContext.ts\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nconst asyncLocalStorage = new AsyncLocalStorage\u003cMap\u003cstring, any\u003e\u003e();\n\nexport function runWithContext\u003cT\u003e(fn: () =\u003e T) {\n\treturn asyncLocalStorage.run(new Map(), fn);\n}\n\nexport function setRequestData\u003cT\u003e(key: string, value: T) {\n\tconst store = asyncLocalStorage.getStore();\n\tif (store) {\n\t\tstore.set(key, value);\n\t} else {\n\t\tconsole.error('AsyncLocalStorage store is not available');\n\t}\n}\n\nexport function getRequestData\u003cT\u003e(key: string): T | undefined {\n\tconst store = asyncLocalStorage.getStore();\n\treturn store ? store.get(key) : undefined;\n}\n```\n\n### 3. Accessing the Stored Data\n\nThe user information stored in AsyncLocalStorage can be accessed from other modules, such as in the authentication helper:\n\n```typescript\n// src/lib/server/authUser.ts\nimport { getRequestData } from '$lib/server/requestContext';\nimport type { AuthUser } from '$lib/types/authUser';\n\nexport function getAuthenticatedUser() {\n\treturn getRequestData\u003cAuthUser\u003e('user');\n}\n```\n\n\u003e [!WARNING]\n\u003e Node.js' AsyncLocalStorage is only available on the server. It cannot be used in client-side code.\n\n## Getting Started\n\n1. Install dependencies with your package manager (e.g., `pnpm install`).\n2. Run the development server with `pnpm dev`.\n3. Explore the code in the `src/hooks.server.ts` and `src/lib/server/` directories to see how AsyncLocalStorage is integrated.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxiviper117%2Fexample-asynclocalstorage-sveltekit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaxiviper117%2Fexample-asynclocalstorage-sveltekit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxiviper117%2Fexample-asynclocalstorage-sveltekit/lists"}