#Type safety for Astro sessions
3 messages · Page 1 of 1 (latest)
To enable type safety for your Astro session data, you need to:
-
Create or update
src/env.d.tswith your session data types, e.g.:declare namespace App { interface SessionData { user: { id: string; name: string }; cart: string[]; } }This step ensures that TypeScript knows the expected structure of your session data and provides type checking and autocompletion in your editor.
-
Ensure your TypeScript configuration includes
src/env.d.ts.
If you have atsconfig.json, make sure it includes all relevant files (including.astro/types.d.tsand yourenv.d.ts). For example:{ "extends": "astro/tsconfigs/base", "include": [".astro/types.d.ts", "**/*"], "exclude": ["dist"] }This ensures TypeScript picks up your global type declarations and applies them project-wide TypeScript configuration Breaking Changes.
-
Restart your TypeScript server or editor after making these changes. Sometimes, the editor needs to reload the new types to provide correct type checking.
If you have done all of the above and are still seeing any for your session values, double-check:
- The file is named exactly
env.d.tsand is located in thesrc/directory. - There are no top-level imports or exports in your
env.d.tsfile, as this would prevent it from being treated as a global type declaration Extending global types. - Your editor or IDE has reloaded the TypeScript project after the changes.
If you follow these steps, you should get type safety and autocompletion for your session data, e.g.:
---
// const cart: string[] | undefined
const cart = await Astro.session?.get('cart');
---