Session
Introduction
The Commercetools Session ctpSession
is a guard of the httpSession
and only available in methods resolving GraphQL endpoints. It is not available in webhooks and events.
The ctpSession
provides functions and setter methods for you to manipulate a session.
Authentication
The customerToken
and customerId
will be set whenever a customer is authenticated. When an unauthenticated customer (guest) opens a cart we will create an anonymous customerToken
and store it in the session. In this case, the customerId will remain empty.
When an anonymous token is present in the session during the customer sign in process, the active anonymous cart will get merged with the customer cart. Any orders placed by this anonymous customer will also be transferred to the signed in customers account.
Only use the ctpSession
in places with access to GraphQL context. Webhooks and event handlers have no reliable access to httpSession. Therefore, in these locations no requests that require customer authentication should be made.
Format
type CtpSession = {
token: CtpAuthToken; // Set when customer has registered or opened cart as anonymous guest
customerId: string; // Only set when customer has registered
cartId: string;
lastOrderId: string;
};
export type CtpAuthToken = {
accessToken: string;
refreshToken?: string;
expirationTime: number;
};
Reading/Getting a session
To interact with the ctpSession
object, it needs to be injected into a class first and then accessing it from the class methods.
const { token, customerId, cartId, lastOrderId } = this.ctpSession;
Mutating a session
Mutating the session can be done trough both a set of regular as setter
methods on the session class.
// ctpSession methods
this.ctpSession.signin(customerToken, customerId); // customerId is protected and can only be set trough the signin method
this.ctpSession.hasValidToken(); // return boolean based on check if expirationTime is before now
this.ctpSession.clear(); // Clear full session
// ctpSession setters
this.ctpSession.token = token;
this.ctpSession.cartId = cartId;
this.ctpSession.lastOrderId = orderId;