@types/express-session
- Version 1.18.1
- Published
- 24.8 kB
- 1 dependency
- MIT license
Install
npm i @types/express-session
yarn add @types/express-session
pnpm add @types/express-session
Overview
TypeScript definitions for express-session
Index
Functions
Classes
Interfaces
Namespaces
Functions
function session
session: typeof session;
Classes
class Cookie
class Cookie implements CookieOptions {}
property domain
domain?: string;
property expires
expires?: Date;
property httpOnly
httpOnly?: boolean;
property maxAge
maxAge?: number;
property originalMaxAge
originalMaxAge: number;
Returns the original
maxAge
(time-to-live), in milliseconds, of the session cookie.
property path
path?: string;
property sameSite
sameSite?: boolean | 'lax' | 'strict' | 'none';
property secure
secure?: boolean | 'auto';
property signed
signed?: boolean;
class MemoryStore
class MemoryStore extends Store {}
**Warning:** the default server-side session storage,
MemoryStore
, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is only meant for debugging and developing.
method all
all: ( callback: (err: any, obj?: { [sid: string]: SessionData }) => void) => void;
method clear
clear: (callback?: (err?: any) => void) => void;
method destroy
destroy: (sid: string, callback?: (err?: any) => void) => void;
method get
get: ( sid: string, callback: (err: any, session?: SessionData | null) => void) => void;
method length
length: (callback: (err: any, length?: number) => void) => void;
method set
set: (sid: string, session: SessionData, callback?: (err?: any) => void) => void;
method touch
touch: (sid: string, session: SessionData, callback?: () => void) => void;
class Session
class Session {}
property cookie
cookie: Cookie;
Each session has a unique cookie object accompany it. This allows you to alter the session cookie per visitor. For example we can set
req.session.cookie.expires
tofalse
to enable the cookie to remain for only the duration of the user-agent.
property id
id: string;
Each session has a unique ID associated with it. This property is an alias of
req.sessionID
and cannot be modified. It has been added to make the session ID accessible from the session object.
method destroy
destroy: (callback: (err: any) => void) => this;
Destroys the session and will unset the
req.session
property. Once complete, thecallback
will be invoked.
method regenerate
regenerate: (callback: (err: any) => void) => this;
To regenerate the session simply invoke the method. Once complete, a new SID and
Session
instance will be initialized atreq.session
and thecallback
will be invoked.
method reload
reload: (callback: (err: any) => void) => this;
Reloads the session data from the store and re-populates the
req.session
object. Once complete, thecallback
will be invoked.
method resetMaxAge
resetMaxAge: () => this;
Resets the cookie's
maxAge
tooriginalMaxAge
See Also
Cookie
method save
save: (callback?: (err: any) => void) => this;
Save the session back to the store, replacing the contents on the store with the contents in memory (though a store may do something else - consult the store's documentation for exact behavior).
This method is automatically called at the end of the HTTP response if the session data has been altered (though this behavior can be altered with various options in the middleware constructor). Because of this, typically this method does not need to be called. There are some cases where it is useful to call this method, for example: redirects, long-lived requests or in WebSockets.
method touch
touch: () => this;
Updates the
maxAge
property. Typically this is not necessary to call, as the session middleware does this for you.
class Store
abstract class Store extends EventEmitter {}
method all
all: ( callback: ( err: any, obj?: SessionData[] | { [sid: string]: SessionData } ) => void) => void;
Returns all sessions in the store
method clear
clear: (callback?: (err?: any) => void) => void;
Delete all sessions from the store.
method createSession
createSession: ( req: express.Request, session: SessionData) => Session & SessionData;
method destroy
abstract destroy: (sid: string, callback?: (err?: any) => void) => void;
Destroys the session with the given session ID.
method get
abstract get: ( sid: string, callback: (err: any, session?: SessionData | null) => void) => void;
Gets the session from the store given a session ID and passes it to
callback
.The
session
argument should be aSession
object if found, otherwisenull
orundefined
if the session was not found and there was no error. A special case is made whenerror.code === 'ENOENT'
to act likecallback(null, null)
.
method length
length: (callback: (err: any, length?: number) => void) => void;
Returns the amount of sessions in the store.
method load
load: (sid: string, callback: (err: any, session?: SessionData) => any) => void;
method regenerate
regenerate: (req: express.Request, callback: (err?: any) => any) => void;
method set
abstract set: ( sid: string, session: SessionData, callback?: (err?: any) => void) => void;
Upsert a session in the store given a session ID and
SessionData
method touch
touch: (sid: string, session: SessionData, callback?: () => void) => void;
"Touches" a given session, resetting the idle timer.
Interfaces
interface CookieOptions
interface CookieOptions {}
property domain
domain?: string | undefined;
Specifies the value for the
Domain Set-Cookie
attribute. By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
property encode
encode?: ((val: string) => string) | undefined;
property expires
expires?: Date | null | undefined;
Specifies the
Date
object to be the value for theExpires Set-Cookie
attribute. By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application.If both
expires
andmaxAge
are set in the options, then the last one defined in the object is what is used.See Also
maxAge
Deprecated
The
expires
option should not be set directly; instead only use themaxAge
option
property httpOnly
httpOnly?: boolean | undefined;
Specifies the boolean value for the
HttpOnly Set-Cookie
attribute. When truthy, theHttpOnly
attribute is set, otherwise it is not. By default, theHttpOnly
attribute is set.Be careful when setting this to
true
, as compliant clients will not allow client-side JavaScript to see the cookie indocument.cookie
.
property maxAge
maxAge?: number | undefined;
Specifies the number (in milliseconds) to use when calculating the
Expires Set-Cookie
attribute. This is done by taking the current server time and addingmaxAge
milliseconds to the value to calculate anExpires
datetime. By default, no maximum age is set.If both
expires
andmaxAge
are set in the options, then the last one defined in the object is what is used.maxAge
should be preferred overexpires
.See Also
expires
property partitioned
partitioned?: boolean | undefined;
Specifies the
boolean
value for the [Partitioned
Set-Cookie
](https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/) attribute. When truthy, thePartitioned
attribute is set, otherwise it is not. By default, thePartitioned
attribute is not set.**Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
property path
path?: string | undefined;
Specifies the value for the
Path Set-Cookie
attribute. By default, this is set to '/', which is the root path of the domain.
property priority
priority?: 'low' | 'medium' | 'high' | undefined;
Specifies the
string
to be the value for the [Priority
Set-Cookie
attribute](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).-
'low'
will set thePriority
attribute toLow
. -'medium'
will set thePriority
attribute toMedium
, the default priority when not set. -'high'
will set thePriority
attribute toHigh
.More information about the different priority levels can be found in [the specification](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).
**Note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
property sameSite
sameSite?: boolean | 'lax' | 'strict' | 'none' | undefined;
Specifies the boolean or string to be the value for the
SameSite Set-Cookie
attribute. -true
will set theSameSite
attribute toStrict
for strict same site enforcement. -false
will not set theSameSite
attribute. -lax
will set theSameSite
attribute toLax
for lax same site enforcement. -none
will set theSameSite
attribute toNone
for an explicit cross-site cookie. -strict
will set theSameSite
attribute toStrict
for strict same site enforcement.More information about the different enforcement levels can be found in the specification.
**Note:** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
property secure
secure?: boolean | 'auto' | undefined;
Specifies the boolean value for the
Secure Set-Cookie
attribute. When truthy, theSecure
attribute is set, otherwise it is not. By default, theSecure
attribute is not set. Be careful when setting this to true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection.Please note that
secure: true
is a **recommended option**. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. Ifsecure
is set, and you access your site over HTTP, **the cookie will not be set**.The cookie.secure option can also be set to the special value
auto
to have this setting automatically match the determined security of the connection. Be careful when using this setting if the site is available both as HTTP and HTTPS, as once the cookie is set on HTTPS, it will no longer be visible over HTTP. This is useful when the Express "trust proxy" setting is properly setup to simplify development vs production configuration.If you have your node.js behind a proxy and are using
secure: true
, you need to set "trust proxy" in express. Please see the [README](https://github.com/expressjs/session) for details.Please see the [README](https://github.com/expressjs/session) for an example of using secure cookies in production, but allowing for testing in development based on NODE_ENV.
property signed
signed?: boolean | undefined;
interface SessionData
interface SessionData {}
This interface allows you to declare additional properties on your session object using [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html).
Example 1
declare module 'express-session' { interface SessionData { views: number; } }
property cookie
cookie: Cookie;
interface SessionOptions
interface SessionOptions {}
property cookie
cookie?: CookieOptions | undefined;
Settings object for the session ID cookie.
See Also
CookieOptions
property name
name?: string | undefined;
The name of the session ID cookie to set in the response (and read from in the request). The default value is 'connect.sid'.
Note if you have multiple apps running on the same hostname (this is just the name, i.e.
localhost
or127.0.0.1
; different schemes and ports do not name a different hostname), then you need to separate the session cookies from each other. The simplest method is to simply set different names per app.
property proxy
proxy?: boolean | undefined;
Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto" header). The default value is undefined.
-
true
: TheX-Forwarded-Proto
header will be used. -false
: All headers are ignored and the connection is considered secure only if there is a direct TLS/SSL connection. -undefined
: Uses the "trust proxy" setting from express
property resave
resave?: boolean | undefined;
Forces the session to be saved back to the session store, even if the session was never modified during the request. Depending on your store this may be necessary, but it can also create race conditions where a client makes two parallel requests to your server and changes made to the session in one request may get overwritten when the other request ends, even if it made no changes (this behavior also depends on what store you're using).
The default value is
true
, but using the default has been deprecated, as the default will change in the future. Please research into this setting and choose what is appropriate to your use-case. Typically, you'll wantfalse
.How do I know if this is necessary for my store? The best way to know is to check with your store if it implements the
touch
method. If it does, then you can safely setresave: false
. If it does not implement thetouch
method and your store sets an expiration date on stored sessions, then you likely needresave: true
.
property rolling
rolling?: boolean | undefined;
Force the session identifier cookie to be set on every response. The expiration is reset to the original
maxAge
, resetting the expiration countdown. The default value isfalse
.With this enabled, the session identifier cookie will expire in
maxAge
*since the last response was sent* instead of inmaxAge
*since the session was last modified by the server*. This is typically used in conjuction with short, non-session-lengthmaxAge
values to provide a quick timeout of the session data with reduced potential of it occurring during on going server interactions.Note that when this option is set to
true
but thesaveUninitialized
option is set tofalse
, the cookie will not be set on a response with an uninitialized session. This option only modifies the behavior when an existing session was loaded for the request.See Also
saveUninitialized
property saveUninitialized
saveUninitialized?: boolean | undefined;
Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified. Choosing
false
is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie. Choosingfalse
will also help with race conditions where a client makes multiple parallel requests without a session.The default value is
true
, but using the default has been deprecated, as the default will change in the future. Please research into this setting and choose what is appropriate to your use-case.**If you are using
express-session
in conjunction with PassportJS:** Passport will add an empty Passport object to the session for use after a user is authenticated, which will be treated as a modification to the session, causing it to be saved. This has been fixed in PassportJS 0.3.0.
property secret
secret: CipherKey | CipherKey[];
This is the secret used to sign the session ID cookie. The secret can be any type of value that is supported by Node.js
crypto.createHmac
(like a string or a Buffer). This can be either a single secret, or an array of multiple secrets. If an array of secrets is provided, only the first element will be used to sign the session ID cookie, while all the elements will be considered when verifying the signature in requests. The secret itself should be not easily parsed by a human and would best be a random set of characters.A best practice may include: * The use of environment variables to store the secret, ensuring the secret itself does not exist in your repository. * Periodic updates of the secret, while ensuring the previous secret is in the array.
Using a secret that cannot be guessed will reduce the ability to hijack a session to only guessing the session ID (as determined by the
genid
option).Changing the secret value will invalidate all existing sessions. In order to rotate the secret without invalidating sessions, provide an array of secrets, with the new secret as first element of the array, and including previous secrets as the later elements.
Note HMAC-256 is used to sign the session ID. For this reason, the secret should contain at least 32 bytes of entropy.
property store
store?: Store | undefined;
The session store instance, defaults to a new
MemoryStore
instance.See Also
MemoryStore
property unset
unset?: 'destroy' | 'keep' | undefined;
Control the result of unsetting req.session (through delete, setting to null, etc.). -
destroy
: The session will be destroyed (deleted) when the response ends. -keep
: The session in the store will be kept, but modifications made during the request are ignored and not saved. 'keep'
method genid
genid: (req: express.Request) => string;
Function to call to generate a new session ID. Provide a function that returns a string that will be used as a session ID. The function is given the request as the first argument if you want to use some value attached to it when generating the ID.
The default value is a function which uses the uid-safe library to generate IDs. Be careful to generate unique IDs so your sessions do not conflict.
Namespaces
namespace global
namespace global {}
namespace global.Express
namespace global.Express {}
interface Request
interface Request {}
property session
session: session.Session & Partial<session.SessionData>;
This request's
Session
object. Even though this property isn't marked as optional, it won't exist until you use theexpress-session
middleware [Declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to add your own properties.See Also
SessionData
property sessionID
sessionID: string;
This request's session ID. Even though this property isn't marked as optional, it won't exist until you use the
express-session
middleware
property sessionStore
sessionStore: SessionStore;
The Store in use. Even though this property isn't marked as optional, it won't exist until you use the
express-session
middleware The functiongenerate
is added by express-session
type SessionStore
type SessionStore = session.Store & { generate: (req: Request) => void };
Package Files (1)
Dependencies (1)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@types/express-session
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@types/express-session)
- HTML<a href="https://www.jsdocs.io/package/@types/express-session"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 3218 ms. - Missing or incorrect documentation? Open an issue for this package.