createSession: async()

in packages/better-auth/src/db/internal-adapter.ts [209:280]


		createSession: async (
			userId: string,
			ctx: GenericEndpointContext,
			dontRememberMe?: boolean,
			override?: Partial<Session> & Record<string, any>,
			overrideAll?: boolean,
		) => {
			const headers = ctx.headers || ctx.request?.headers;
			const { id: _, ...rest } = override || {};
			const data: Omit<Session, "id"> = {
				ipAddress:
					ctx.request || ctx.headers
						? getIp(ctx.request || ctx.headers!, ctx.context.options) || ""
						: "",
				userAgent: headers?.get("user-agent") || "",
				...rest,
				/**
				 * If the user doesn't want to be remembered
				 * set the session to expire in 1 day.
				 * The cookie will be set to expire at the end of the session
				 */
				expiresAt: dontRememberMe
					? getDate(60 * 60 * 24, "sec") // 1 day
					: getDate(sessionExpiration, "sec"),
				userId,
				token: generateId(32),
				createdAt: new Date(),
				updatedAt: new Date(),
				...(overrideAll ? rest : {}),
			};
			const res = await createWithHooks(
				data,
				"session",
				secondaryStorage
					? {
							fn: async (sessionData) => {
								/**
								 * store the session token for the user
								 * so we can retrieve it later for listing sessions
								 */
								const currentList = await secondaryStorage.get(
									`active-sessions-${userId}`,
								);

								let list: { token: string; expiresAt: number }[] = [];
								const now = Date.now();

								if (currentList) {
									list = safeJSONParse(currentList) || [];
									list = list.filter((session) => session.expiresAt > now);
								}

								list.push({
									token: data.token,
									expiresAt: now + sessionExpiration * 1000,
								});

								await secondaryStorage.set(
									`active-sessions-${userId}`,
									JSON.stringify(list),
									sessionExpiration,
								);

								return sessionData;
							},
							executeMainFn: options.session?.storeSessionInDatabase,
						}
					: undefined,
				ctx,
			);
			return res as Session;
		},