@commercengine/storefront-sdk-nextjs 0.1.0-alpha.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs DELETED
@@ -1,411 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/index.ts
32
- var index_exports = {};
33
- __export(index_exports, {
34
- ClientTokenStorage: () => ClientTokenStorage,
35
- ServerTokenStorage: () => ServerTokenStorage,
36
- getStorefrontSDK: () => getStorefrontSDK,
37
- storefront: () => storefront
38
- });
39
- module.exports = __toCommonJS(index_exports);
40
-
41
- // src/sdk-manager.ts
42
- var import_react = require("react");
43
- var import_storefront_sdk = require("@commercengine/storefront-sdk");
44
-
45
- // src/token-storage.ts
46
- var ClientTokenStorage = class {
47
- constructor(options = {}) {
48
- const prefix = options.prefix || "ce_";
49
- this.accessTokenKey = `${prefix}access_token`;
50
- this.refreshTokenKey = `${prefix}refresh_token`;
51
- this.options = {
52
- maxAge: options.maxAge || 30 * 24 * 60 * 60,
53
- // 30 days default
54
- path: options.path || "/",
55
- domain: options.domain,
56
- secure: options.secure ?? (typeof window !== "undefined" && window.location?.protocol === "https:"),
57
- sameSite: options.sameSite || "Lax"
58
- };
59
- }
60
- async getAccessToken() {
61
- return this.getCookie(this.accessTokenKey);
62
- }
63
- async setAccessToken(token) {
64
- this.setCookie(this.accessTokenKey, token);
65
- }
66
- async getRefreshToken() {
67
- return this.getCookie(this.refreshTokenKey);
68
- }
69
- async setRefreshToken(token) {
70
- this.setCookie(this.refreshTokenKey, token);
71
- }
72
- async clearTokens() {
73
- this.deleteCookie(this.accessTokenKey);
74
- this.deleteCookie(this.refreshTokenKey);
75
- }
76
- getCookie(name) {
77
- if (typeof document === "undefined") return null;
78
- const value = `; ${document.cookie}`;
79
- const parts = value.split(`; ${name}=`);
80
- if (parts.length === 2) {
81
- const cookieValue = parts.pop()?.split(";").shift();
82
- return cookieValue ? decodeURIComponent(cookieValue) : null;
83
- }
84
- return null;
85
- }
86
- setCookie(name, value) {
87
- if (typeof document === "undefined") return;
88
- const encodedValue = encodeURIComponent(value);
89
- let cookieString = `${name}=${encodedValue}`;
90
- if (this.options.maxAge) {
91
- cookieString += `; Max-Age=${this.options.maxAge}`;
92
- }
93
- if (this.options.path) {
94
- cookieString += `; Path=${this.options.path}`;
95
- }
96
- if (this.options.domain) {
97
- cookieString += `; Domain=${this.options.domain}`;
98
- }
99
- if (this.options.secure) {
100
- cookieString += `; Secure`;
101
- }
102
- if (this.options.sameSite) {
103
- cookieString += `; SameSite=${this.options.sameSite}`;
104
- }
105
- document.cookie = cookieString;
106
- }
107
- deleteCookie(name) {
108
- if (typeof document === "undefined") return;
109
- let cookieString = `${name}=; Max-Age=0`;
110
- if (this.options.path) {
111
- cookieString += `; Path=${this.options.path}`;
112
- }
113
- if (this.options.domain) {
114
- cookieString += `; Domain=${this.options.domain}`;
115
- }
116
- document.cookie = cookieString;
117
- }
118
- };
119
- var ServerTokenStorage = class {
120
- constructor(cookieStore, options = {}) {
121
- const prefix = options.prefix || "ce_";
122
- this.accessTokenKey = `${prefix}access_token`;
123
- this.refreshTokenKey = `${prefix}refresh_token`;
124
- this.cookieStore = cookieStore;
125
- this.options = {
126
- maxAge: options.maxAge || 30 * 24 * 60 * 60,
127
- // 30 days default
128
- path: options.path || "/",
129
- domain: options.domain,
130
- secure: options.secure ?? process.env.NODE_ENV === "production",
131
- sameSite: options.sameSite || "Lax"
132
- };
133
- }
134
- async getAccessToken() {
135
- try {
136
- return this.cookieStore.get(this.accessTokenKey)?.value || null;
137
- } catch (error) {
138
- console.warn(`Could not get access token from server cookies:`, error);
139
- return null;
140
- }
141
- }
142
- async setAccessToken(token) {
143
- try {
144
- this.cookieStore.set(this.accessTokenKey, token, {
145
- maxAge: this.options.maxAge,
146
- path: this.options.path,
147
- domain: this.options.domain,
148
- secure: this.options.secure,
149
- sameSite: this.options.sameSite?.toLowerCase(),
150
- httpOnly: false
151
- // Allow client-side access for SDK flexibility
152
- });
153
- } catch (error) {
154
- console.warn(`Could not set access token on server:`, error);
155
- }
156
- }
157
- async getRefreshToken() {
158
- try {
159
- return this.cookieStore.get(this.refreshTokenKey)?.value || null;
160
- } catch (error) {
161
- console.warn(`Could not get refresh token from server cookies:`, error);
162
- return null;
163
- }
164
- }
165
- async setRefreshToken(token) {
166
- try {
167
- this.cookieStore.set(this.refreshTokenKey, token, {
168
- maxAge: this.options.maxAge,
169
- path: this.options.path,
170
- domain: this.options.domain,
171
- secure: this.options.secure,
172
- sameSite: this.options.sameSite?.toLowerCase(),
173
- httpOnly: false
174
- // Allow client-side access for SDK flexibility
175
- });
176
- } catch (error) {
177
- console.warn(`Could not set refresh token on server:`, error);
178
- }
179
- }
180
- async clearTokens() {
181
- try {
182
- this.cookieStore.delete(this.accessTokenKey);
183
- this.cookieStore.delete(this.refreshTokenKey);
184
- } catch (error) {
185
- console.warn(`Could not clear tokens on server:`, error);
186
- }
187
- }
188
- };
189
-
190
- // src/build-token-cache.ts
191
- var store = /* @__PURE__ */ new Map();
192
- function isExpired(token) {
193
- if (!token) return true;
194
- if (!token.expiresAt) return false;
195
- return Date.now() > token.expiresAt - 3e4;
196
- }
197
- function getCachedToken(key) {
198
- const token = store.get(key);
199
- return isExpired(token) ? null : token;
200
- }
201
- function setCachedToken(key, token) {
202
- const expiresAt = token.ttlSeconds != null ? Date.now() + token.ttlSeconds * 1e3 : void 0;
203
- store.set(key, {
204
- accessToken: token.accessToken,
205
- refreshToken: token.refreshToken ?? null,
206
- expiresAt
207
- });
208
- }
209
- function clearCachedToken(key) {
210
- store.delete(key);
211
- }
212
-
213
- // src/build-caching-memory-storage.ts
214
- var DEFAULT_TTL_SECONDS = 5 * 60;
215
- var BuildCachingMemoryTokenStorage = class {
216
- constructor(cacheKey, ttlSeconds = DEFAULT_TTL_SECONDS) {
217
- this.cacheKey = cacheKey;
218
- this.ttlSeconds = ttlSeconds;
219
- this.access = null;
220
- this.refresh = null;
221
- }
222
- async getAccessToken() {
223
- if (this.access) {
224
- console.log(`\u{1F535} [BuildCache] Using instance token for key: ${this.cacheKey}`);
225
- return this.access;
226
- }
227
- const cached = getCachedToken(this.cacheKey);
228
- if (cached?.accessToken) {
229
- console.log(`\u{1F7E2} [BuildCache] Using cached token for key: ${this.cacheKey}`);
230
- this.access = cached.accessToken;
231
- this.refresh = cached.refreshToken ?? null;
232
- return this.access;
233
- }
234
- console.log(`\u{1F7E1} [BuildCache] No cached token found for key: ${this.cacheKey}`);
235
- return null;
236
- }
237
- async setAccessToken(token) {
238
- console.log(`\u{1F7E0} [BuildCache] Caching new access token for key: ${this.cacheKey}`);
239
- this.access = token;
240
- setCachedToken(this.cacheKey, {
241
- accessToken: token,
242
- refreshToken: this.refresh,
243
- ttlSeconds: this.ttlSeconds
244
- });
245
- }
246
- async getRefreshToken() {
247
- return this.refresh;
248
- }
249
- async setRefreshToken(token) {
250
- this.refresh = token;
251
- setCachedToken(this.cacheKey, {
252
- accessToken: this.access ?? "",
253
- refreshToken: token,
254
- ttlSeconds: this.ttlSeconds
255
- });
256
- }
257
- async clearTokens() {
258
- this.access = null;
259
- this.refresh = null;
260
- clearCachedToken(this.cacheKey);
261
- }
262
- };
263
-
264
- // src/sdk-manager.ts
265
- var globalConfig = null;
266
- function getEnvConfig() {
267
- return {
268
- storeId: process.env.NEXT_PUBLIC_STORE_ID || "",
269
- environment: process.env.NEXT_PUBLIC_ENVIRONMENT === "production" ? import_storefront_sdk.Environment.Production : import_storefront_sdk.Environment.Staging,
270
- apiKey: process.env.NEXT_PUBLIC_API_KEY
271
- };
272
- }
273
- function getConfig() {
274
- if (globalConfig) {
275
- return globalConfig;
276
- }
277
- return getEnvConfig();
278
- }
279
- var clientSDK = null;
280
- function hasRequestContext() {
281
- try {
282
- const { cookies } = require("next/headers");
283
- cookies();
284
- return true;
285
- } catch {
286
- return false;
287
- }
288
- }
289
- function createTokenStorage(cookieStore, options, config) {
290
- if (typeof window !== "undefined") {
291
- return new ClientTokenStorage(options);
292
- }
293
- if (cookieStore) {
294
- return new ServerTokenStorage(cookieStore, options);
295
- }
296
- const shouldCache = process.env.NEXT_BUILD_CACHE_TOKENS === "true";
297
- if (shouldCache && config) {
298
- const cacheKey = `${config.storeId}:${config.environment || "production"}`;
299
- console.log(`\u{1F680} [BuildCache] Using BuildCachingMemoryTokenStorage with key: ${cacheKey}`);
300
- return new BuildCachingMemoryTokenStorage(cacheKey);
301
- }
302
- console.log(`\u{1F504} [Build] Using standard MemoryTokenStorage (caching disabled)`);
303
- return new import_storefront_sdk.MemoryTokenStorage();
304
- }
305
- var getServerSDKCached = (0, import_react.cache)((cookieStore) => {
306
- const config = getEnvConfig();
307
- return new import_storefront_sdk.StorefrontSDK({
308
- ...config,
309
- tokenStorage: createTokenStorage(
310
- cookieStore,
311
- config.tokenStorageOptions,
312
- config
313
- )
314
- });
315
- });
316
- var buildTimeSDK = null;
317
- function getBuildTimeSDK() {
318
- const config = getEnvConfig();
319
- if (!buildTimeSDK) {
320
- buildTimeSDK = new import_storefront_sdk.StorefrontSDK({
321
- ...config,
322
- tokenStorage: createTokenStorage(
323
- void 0,
324
- config.tokenStorageOptions,
325
- config
326
- )
327
- });
328
- }
329
- return buildTimeSDK;
330
- }
331
- function getStorefrontSDK(cookieStore) {
332
- if (typeof window !== "undefined") {
333
- if (cookieStore) {
334
- console.warn(
335
- "Cookie store passed in client environment - this will be ignored"
336
- );
337
- }
338
- const config = getConfig();
339
- if (!clientSDK) {
340
- clientSDK = new import_storefront_sdk.StorefrontSDK({
341
- ...config,
342
- tokenStorage: createTokenStorage(
343
- void 0,
344
- config.tokenStorageOptions,
345
- config
346
- )
347
- });
348
- }
349
- return clientSDK;
350
- }
351
- if (cookieStore) {
352
- return getServerSDKCached(cookieStore);
353
- }
354
- if (hasRequestContext()) {
355
- let autoDetectMessage = "";
356
- try {
357
- require.resolve("next/headers");
358
- autoDetectMessage = `
359
-
360
- \u{1F50D} Auto-detection attempted but failed. You may be in:
361
- - Server Action (use: const sdk = getStorefrontSDK(await cookies()))
362
- - API Route (use: const sdk = getStorefrontSDK(cookies()))
363
- - Server Component in App Router (use: const sdk = getStorefrontSDK(cookies()))
364
- `;
365
- } catch {
366
- autoDetectMessage = `
367
-
368
- \u{1F4A1} Make sure you have Next.js installed and are in a server context.
369
- `;
370
- }
371
- throw new Error(
372
- `
373
- \u{1F6A8} Server Environment Detected!
374
-
375
- You're calling getStorefrontSDK() on the server without cookies.
376
- Please pass the Next.js cookie store:
377
-
378
- \u2705 Correct usage:
379
- import { cookies } from 'next/headers';
380
-
381
- // Server Actions & Route Handlers
382
- const sdk = getStorefrontSDK(await cookies());
383
-
384
- // API Routes & Server Components (App Router)
385
- const sdk = getStorefrontSDK(cookies());
386
-
387
- \u274C Your current usage:
388
- const sdk = getStorefrontSDK(); // Missing cookies!
389
- ${autoDetectMessage}
390
- This is required for server-side token access.
391
- `.trim()
392
- );
393
- }
394
- return getBuildTimeSDK();
395
- }
396
-
397
- // src/storefront.ts
398
- function storefront(cookieStore) {
399
- return getStorefrontSDK(cookieStore);
400
- }
401
-
402
- // src/index.ts
403
- __reExport(index_exports, require("@commercengine/storefront-sdk"), module.exports);
404
- // Annotate the CommonJS export names for ESM import in node:
405
- 0 && (module.exports = {
406
- ClientTokenStorage,
407
- ServerTokenStorage,
408
- getStorefrontSDK,
409
- storefront,
410
- ...require("@commercengine/storefront-sdk")
411
- });
package/dist/index.d.cts DELETED
@@ -1,107 +0,0 @@
1
- import { TokenStorage, StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
2
- export * from '@commercengine/storefront-sdk';
3
- export { StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
4
- export { default as storefront } from './storefront.cjs';
5
-
6
- /**
7
- * Configuration options for NextJSTokenStorage
8
- */
9
- interface NextJSTokenStorageOptions {
10
- /**
11
- * Prefix for cookie names (default: "ce_")
12
- */
13
- prefix?: string;
14
- /**
15
- * Maximum age of cookies in seconds (default: 30 days)
16
- */
17
- maxAge?: number;
18
- /**
19
- * Cookie path (default: "/")
20
- */
21
- path?: string;
22
- /**
23
- * Cookie domain (default: current domain)
24
- */
25
- domain?: string;
26
- /**
27
- * Whether cookies should be secure (default: auto-detect based on environment)
28
- */
29
- secure?: boolean;
30
- /**
31
- * SameSite cookie attribute (default: "Lax")
32
- */
33
- sameSite?: "Strict" | "Lax" | "None";
34
- }
35
- /**
36
- * Client-side token storage that uses document.cookie
37
- */
38
- declare class ClientTokenStorage implements TokenStorage {
39
- private accessTokenKey;
40
- private refreshTokenKey;
41
- private options;
42
- constructor(options?: NextJSTokenStorageOptions);
43
- getAccessToken(): Promise<string | null>;
44
- setAccessToken(token: string): Promise<void>;
45
- getRefreshToken(): Promise<string | null>;
46
- setRefreshToken(token: string): Promise<void>;
47
- clearTokens(): Promise<void>;
48
- private getCookie;
49
- private setCookie;
50
- private deleteCookie;
51
- }
52
- type NextCookieStore$1 = {
53
- get: (name: string) => {
54
- value: string;
55
- } | undefined;
56
- set: (name: string, value: string, options?: any) => void;
57
- delete: (name: string) => void;
58
- };
59
- /**
60
- * Server-side token storage that uses Next.js cookies API
61
- */
62
- declare class ServerTokenStorage implements TokenStorage {
63
- private accessTokenKey;
64
- private refreshTokenKey;
65
- private options;
66
- private cookieStore;
67
- constructor(cookieStore: NextCookieStore$1, options?: NextJSTokenStorageOptions);
68
- getAccessToken(): Promise<string | null>;
69
- setAccessToken(token: string): Promise<void>;
70
- getRefreshToken(): Promise<string | null>;
71
- setRefreshToken(token: string): Promise<void>;
72
- clearTokens(): Promise<void>;
73
- }
74
-
75
- /**
76
- * Configuration for the NextJS SDK wrapper
77
- */
78
- interface NextJSSDKConfig extends Omit<StorefrontSDKOptions, "tokenStorage"> {
79
- /**
80
- * Token storage configuration options
81
- */
82
- tokenStorageOptions?: NextJSTokenStorageOptions;
83
- }
84
- type NextCookieStore = {
85
- get: (name: string) => {
86
- value: string;
87
- } | undefined;
88
- set: (name: string, value: string, options?: any) => void;
89
- delete: (name: string) => void;
90
- };
91
- /**
92
- * Smart SDK getter that automatically detects environment
93
- *
94
- * Usage:
95
- * - Client-side: getStorefrontSDK()
96
- * - Server-side with request context: getStorefrontSDK(await cookies())
97
- * - SSG/ISR (no request context): getStorefrontSDK() (uses memory storage)
98
- */
99
- declare function getStorefrontSDK(): StorefrontSDK;
100
- declare function getStorefrontSDK(cookieStore: NextCookieStore): StorefrontSDK;
101
- /**
102
- * Initialize the SDK with configuration (internal use)
103
- * This should be called once in your app via StorefrontSDKInitializer
104
- */
105
- declare function initializeStorefrontSDK(config: NextJSSDKConfig): void;
106
-
107
- export { ClientTokenStorage, type NextJSSDKConfig, type NextJSTokenStorageOptions, ServerTokenStorage, getStorefrontSDK, initializeStorefrontSDK as i };
@@ -1,66 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/middleware.ts
21
- var middleware_exports = {};
22
- __export(middleware_exports, {
23
- ensureStorefrontTokens: () => ensureStorefrontTokens
24
- });
25
- module.exports = __toCommonJS(middleware_exports);
26
-
27
- // src/middleware-helper.ts
28
- async function ensureStorefrontTokens(reqCookies, resCookies, opts) {
29
- const prefix = opts.cookiePrefix ?? "ce_";
30
- const ACCESS = `${prefix}access_token`;
31
- const existingAccess = reqCookies.get(ACCESS)?.value;
32
- if (existingAccess) {
33
- return false;
34
- }
35
- try {
36
- const resp = await fetch(`${opts.baseUrl}/auth/anonymous`, {
37
- method: "POST",
38
- headers: {
39
- "Content-Type": "application/json",
40
- ...opts.apiKey ? { "X-Api-Key": opts.apiKey } : {}
41
- }
42
- });
43
- if (!resp.ok) return false;
44
- const data = await resp.json();
45
- const content = data?.content;
46
- if (!content?.access_token || !content?.refresh_token) return false;
47
- const cookieDefaults = {
48
- path: "/",
49
- httpOnly: false,
50
- sameSite: "lax",
51
- secure: opts.cookieOptions?.secure ?? false,
52
- maxAge: 30 * 24 * 60 * 60
53
- // 30 days
54
- };
55
- const finalOpts = { ...cookieDefaults, ...opts.cookieOptions || {} };
56
- resCookies.set(ACCESS, content.access_token, finalOpts);
57
- resCookies.set(`${prefix}refresh_token`, content.refresh_token, finalOpts);
58
- return true;
59
- } catch {
60
- return false;
61
- }
62
- }
63
- // Annotate the CommonJS export names for ESM import in node:
64
- 0 && (module.exports = {
65
- ensureStorefrontTokens
66
- });
@@ -1,38 +0,0 @@
1
- /**
2
- * Minimal cookie interface compatible with Next.js middleware cookies API.
3
- */
4
- interface NextCookiesLike {
5
- get: (name: string) => {
6
- value: string;
7
- } | undefined;
8
- set: (name: string, value: string, options?: {
9
- maxAge?: number;
10
- path?: string;
11
- domain?: string;
12
- secure?: boolean;
13
- sameSite?: "strict" | "lax" | "none" | (string & {});
14
- httpOnly?: boolean;
15
- }) => any;
16
- }
17
- interface EnsureTokensOptions {
18
- baseUrl: string;
19
- apiKey?: string;
20
- cookiePrefix?: string;
21
- cookieOptions?: {
22
- maxAge?: number;
23
- path?: string;
24
- domain?: string;
25
- secure?: boolean;
26
- sameSite?: "strict" | "lax" | "none";
27
- httpOnly?: boolean;
28
- };
29
- }
30
- /**
31
- * Pre-seed anonymous tokens in Next.js middleware when missing.
32
- * Call this early to ensure SSR and client share the same session.
33
- *
34
- * Returns true if tokens were set on the response, false otherwise.
35
- */
36
- declare function ensureStorefrontTokens(reqCookies: NextCookiesLike, resCookies: NextCookiesLike, opts: EnsureTokensOptions): Promise<boolean>;
37
-
38
- export { type EnsureTokensOptions, type NextCookiesLike, ensureStorefrontTokens };
@@ -1,38 +0,0 @@
1
- /**
2
- * Minimal cookie interface compatible with Next.js middleware cookies API.
3
- */
4
- interface NextCookiesLike {
5
- get: (name: string) => {
6
- value: string;
7
- } | undefined;
8
- set: (name: string, value: string, options?: {
9
- maxAge?: number;
10
- path?: string;
11
- domain?: string;
12
- secure?: boolean;
13
- sameSite?: "strict" | "lax" | "none" | (string & {});
14
- httpOnly?: boolean;
15
- }) => any;
16
- }
17
- interface EnsureTokensOptions {
18
- baseUrl: string;
19
- apiKey?: string;
20
- cookiePrefix?: string;
21
- cookieOptions?: {
22
- maxAge?: number;
23
- path?: string;
24
- domain?: string;
25
- secure?: boolean;
26
- sameSite?: "strict" | "lax" | "none";
27
- httpOnly?: boolean;
28
- };
29
- }
30
- /**
31
- * Pre-seed anonymous tokens in Next.js middleware when missing.
32
- * Call this early to ensure SSR and client share the same session.
33
- *
34
- * Returns true if tokens were set on the response, false otherwise.
35
- */
36
- declare function ensureStorefrontTokens(reqCookies: NextCookiesLike, resCookies: NextCookiesLike, opts: EnsureTokensOptions): Promise<boolean>;
37
-
38
- export { type EnsureTokensOptions, type NextCookiesLike, ensureStorefrontTokens };
@@ -1,39 +0,0 @@
1
- // src/middleware-helper.ts
2
- async function ensureStorefrontTokens(reqCookies, resCookies, opts) {
3
- const prefix = opts.cookiePrefix ?? "ce_";
4
- const ACCESS = `${prefix}access_token`;
5
- const existingAccess = reqCookies.get(ACCESS)?.value;
6
- if (existingAccess) {
7
- return false;
8
- }
9
- try {
10
- const resp = await fetch(`${opts.baseUrl}/auth/anonymous`, {
11
- method: "POST",
12
- headers: {
13
- "Content-Type": "application/json",
14
- ...opts.apiKey ? { "X-Api-Key": opts.apiKey } : {}
15
- }
16
- });
17
- if (!resp.ok) return false;
18
- const data = await resp.json();
19
- const content = data?.content;
20
- if (!content?.access_token || !content?.refresh_token) return false;
21
- const cookieDefaults = {
22
- path: "/",
23
- httpOnly: false,
24
- sameSite: "lax",
25
- secure: opts.cookieOptions?.secure ?? false,
26
- maxAge: 30 * 24 * 60 * 60
27
- // 30 days
28
- };
29
- const finalOpts = { ...cookieDefaults, ...opts.cookieOptions || {} };
30
- resCookies.set(ACCESS, content.access_token, finalOpts);
31
- resCookies.set(`${prefix}refresh_token`, content.refresh_token, finalOpts);
32
- return true;
33
- } catch {
34
- return false;
35
- }
36
- }
37
- export {
38
- ensureStorefrontTokens
39
- };