Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ fastify.decodeSecureSession(request.cookies['session'], undefined, 'mySecondSess

## Add TypeScript types

The session data is typed as `{ [key: string]: any }`. This can be extended with [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) to get improved type support.
The session data is defined as an interface called `SessionData`. It can be extended with [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) for improved type support.

```ts
declare module '@fastify/secure-session' {
Expand Down
5 changes: 1 addition & 4 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ declare module "fastify" {
}

type FastifySecureSession = FastifyPluginCallback<fastifySecureSession.SecureSessionPluginOptions | (fastifySecureSession.SecureSessionPluginOptions & Required<Pick<fastifySecureSession.SecureSessionPluginOptions, 'sessionName'>>)[]>;
interface SessionData {}

declare namespace fastifySecureSession {
export type Session<T = SessionData> = Partial<T> & {
Expand All @@ -29,10 +30,6 @@ declare namespace fastifySecureSession {
touch(): void;
}

export interface SessionData {
[key: string]: any;
}

export type SecureSessionPluginOptions = {
cookie?: CookieSerializeOptions
cookieName?: string
Expand Down
8 changes: 7 additions & 1 deletion types/index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ app.get("/not-websockets", async (request, reply) => {
expectType<string | undefined>(request.session.get("foo"));
expectType<any>(request.session.get("baz"));
expectType<string | undefined>(request.session.foo);
expectType<any>(request.session.baz);
expectType<SessionData | undefined>(request.session.data());
request.session.delete();
request.session.options({ maxAge: 42 })
Expand All @@ -51,6 +50,13 @@ app.get("/not-websockets", async (request, reply) => {
request.foo.delete();
request.foo.options({ maxAge: 42 });
request.foo.touch();

// @ts-expect-error: set undefined key
request.session.set("baz", "bar");
// @ts-expect-error: invoke undefined key
expectType<any>(request.session.baz);
// @ts-expect-error: invoke undefined key
request.baz.touch()
});

expectType<Session | null>(app.decodeSecureSession("some cookie"))
Expand Down