fastify-custom-session
![Number of open issues](https://isitmaintained.com/badge/open/ethicdevs/fastify-custom-session.svg)
A Fastify (v3.x+) plugin that let you use session and decide only where to load/save from/to
Installation
$ yarn add @ethicdevs/fastify-custom-session
# or
$ npm i @ethicdevs/fastify-custom-session
Usage
import fastifyCustomSession, {
FirebaseSessionAdapter,
PostgresSessionAdapter,
PrismaSessionAdapter,
} from "@ethicdevs/fastify-custom-session";
let server = null;
function main() {
server = fastify();
server.register(fastifyCustomSession, {
password: "super-secret-session-secret",
cookieName: "my_app_session_id",
cookieOptions: {
domain: `.my-app.com`,
httpOnly: true,
expires: new Date(Date.now() + 10 * (8 * 3600) * 1000),
path: "/",
secure: false,
sameSite: "lax",
signed: true,
},
initialSession: {
whateverYouWant: '<unset>',
aNullableProp: null,
mySuperObject: {
foo: '<unset>',
bar: 0,
baz: '<unset>',
};
},
storeAdapter: new PickedSessionAdapter({
}) as any,
});
}
main();
then if you are a TypeScript user you will need to defined the shape of the
session.data
object, you can do so easily by adding the following lines to your
types/global/index.d.ts
file:
declare module "@ethicdevs/fastify-custom-session" {
declare interface CustomSession {
whateverYouWant: string;
aNullableProp: null | string;
mySuperObject: {
foo: string;
bar: number;
baz: string;
};
}
}
later on during request before you send the headers/response, typically in your controller/handler:
const myRequestHandler = async (request, reply) => {
request.session.data.whateverYouWant = "foo";
request.session.data.aNullableProp = "not null anymore";
request.session.data.mySuperObject = {
foo: "bar",
bar: 42,
baz: "quxx",
};
return reply.send("Hello with session!");
};
const mySecondRequestHandler = async (request, reply) => {
request.session.data.whateverYouWant;
request.session.data.aNullableProp;
request.session.data.object.foo;
request.session.data.object.bar;
return reply.send(
"Cool value from session:" + request.session.data.object.baz,
);
};
then enjoy the session being available both in your controllers/handlers and in
your data store table/collection (linked to the Adapter you chosen in first step).
License
The MIT license.