@akinon/next 2.0.0-beta.12 → 2.0.0-beta.13

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +282 -29
  2. package/api/auth.ts +99 -77
  3. package/api/cache.ts +41 -5
  4. package/api/client.ts +3 -3
  5. package/api/form.ts +85 -0
  6. package/api/image-proxy.ts +75 -0
  7. package/api/product-categories.ts +53 -0
  8. package/api/similar-product-list.ts +63 -0
  9. package/api/similar-products.ts +111 -0
  10. package/api/virtual-try-on.ts +382 -0
  11. package/bin/pz-generate-routes.js +105 -0
  12. package/bin/pz-prebuild.js +1 -1
  13. package/bin/pz-predev.js +1 -0
  14. package/components/accordion.tsx +21 -6
  15. package/components/button.tsx +1 -1
  16. package/components/file-input.tsx +65 -3
  17. package/components/input.tsx +2 -2
  18. package/components/modal.tsx +32 -16
  19. package/components/plugin-module.tsx +61 -3
  20. package/components/select.tsx +2 -2
  21. package/components/selected-payment-option-view.tsx +21 -0
  22. package/data/client/checkout.ts +130 -74
  23. package/data/server/category.ts +11 -9
  24. package/data/server/flatpage.ts +4 -1
  25. package/data/server/form.ts +4 -1
  26. package/data/server/landingpage.ts +4 -1
  27. package/data/server/list.ts +5 -4
  28. package/data/server/menu.ts +4 -1
  29. package/data/server/product.ts +97 -52
  30. package/data/server/seo.ts +4 -1
  31. package/data/server/special-page.ts +5 -4
  32. package/data/server/widget.ts +4 -1
  33. package/data/urls.ts +3 -2
  34. package/hocs/client/with-segment-defaults.tsx +2 -2
  35. package/hocs/server/with-segment-defaults.tsx +65 -20
  36. package/hooks/index.ts +1 -0
  37. package/hooks/use-loyalty-availability.ts +21 -0
  38. package/hooks/use-payment-options.ts +2 -1
  39. package/hooks/use-pz-params.ts +37 -0
  40. package/instrumentation/index.ts +0 -1
  41. package/instrumentation/node.ts +2 -20
  42. package/jest.config.js +7 -1
  43. package/lib/cache-handler.mjs +527 -15
  44. package/lib/cache.ts +260 -31
  45. package/localization/provider.tsx +2 -5
  46. package/middlewares/checkout-provider.ts +1 -1
  47. package/middlewares/complete-gpay.ts +33 -26
  48. package/middlewares/complete-masterpass.ts +34 -26
  49. package/middlewares/complete-wallet.ts +183 -0
  50. package/middlewares/default.ts +346 -235
  51. package/middlewares/index.ts +8 -2
  52. package/middlewares/locale.ts +0 -1
  53. package/middlewares/masterpass-rest-callback.ts +220 -0
  54. package/middlewares/pretty-url.ts +21 -8
  55. package/middlewares/redirection-payment.ts +33 -26
  56. package/middlewares/saved-card-redirection.ts +34 -26
  57. package/middlewares/three-d-redirection.ts +33 -26
  58. package/middlewares/url-redirection.ts +9 -15
  59. package/middlewares/wallet-complete-redirection.ts +207 -0
  60. package/package.json +20 -11
  61. package/plugins.d.ts +19 -4
  62. package/plugins.js +9 -1
  63. package/redux/actions.ts +47 -0
  64. package/redux/middlewares/checkout.ts +20 -8
  65. package/redux/middlewares/index.ts +12 -10
  66. package/redux/middlewares/pre-order/address.ts +1 -1
  67. package/redux/middlewares/pre-order/attribute-based-shipping-option.ts +1 -1
  68. package/redux/middlewares/pre-order/data-source-shipping-option.ts +1 -1
  69. package/redux/middlewares/pre-order/delivery-option.ts +1 -1
  70. package/redux/middlewares/pre-order/index.ts +3 -1
  71. package/redux/middlewares/pre-order/installment-option.ts +2 -1
  72. package/redux/middlewares/pre-order/payment-option-reset.ts +37 -0
  73. package/redux/middlewares/pre-order/payment-option.ts +1 -1
  74. package/redux/middlewares/pre-order/pre-order-validation.ts +4 -3
  75. package/redux/middlewares/pre-order/redirection.ts +2 -2
  76. package/redux/middlewares/pre-order/set-pre-order.ts +2 -2
  77. package/redux/middlewares/pre-order/shipping-option.ts +1 -1
  78. package/redux/middlewares/pre-order/shipping-step.ts +1 -1
  79. package/redux/reducers/checkout.ts +9 -1
  80. package/redux/reducers/index.ts +5 -1
  81. package/sentry/index.ts +54 -17
  82. package/types/commerce/checkout.ts +11 -1
  83. package/types/index.ts +96 -6
  84. package/types/next-auth.d.ts +2 -2
  85. package/utils/app-fetch.ts +2 -2
  86. package/utils/generate-commerce-search-params.ts +3 -2
  87. package/utils/get-checkout-path.ts +3 -0
  88. package/utils/index.ts +38 -11
  89. package/utils/override-middleware.ts +1 -0
  90. package/utils/pz-segments.ts +92 -0
  91. package/utils/redirect-ignore.ts +35 -0
  92. package/utils/redirect.ts +9 -3
  93. package/with-pz-config.js +10 -4
package/CHANGELOG.md CHANGED
@@ -1,78 +1,331 @@
1
1
  # @akinon/next
2
2
 
3
- ## 2.0.0-beta.12
3
+ ## 2.0.0-beta.13
4
4
 
5
5
  ### Minor Changes
6
6
 
7
- - 1d79e32: ZERO-3540: Next.js Upgrade to 15.4.5
7
+ - b12527ec: ZERO-4102: Add support for post-checkout redirect in middleware
8
+ - a9f5cdb1: ZERO-4102: Fix post-checkout condition to additionally check for empty search parameters.
9
+ - 01ee41f1: ZERO-4102: Implement a post-checkout flow by dynamically determining checkout paths and managing a pz-post-checkout-flow cookie.
8
10
 
9
- ## 2.0.0-beta.11
11
+ ## 1.118.0
10
12
 
11
13
  ### Minor Changes
12
14
 
13
- - ac783d6: ZERO-3482: Update tailwindcss to version 4.1.11 and enhance button cursor styles
15
+ - 729fe756: ZERO-3895: improve non-3D payment handling and error display
14
16
 
15
- ## 2.0.0-beta.10
17
+ ## 1.117.0
18
+
19
+ ## 1.116.0
16
20
 
17
21
  ### Minor Changes
18
22
 
19
- - 2806320: ZERO-3390: Update version tailwindcss, autoprefixer, tailwind-merge, postcss
23
+ - d7ec6b08: ZERO-3988: Add Google Pay option to plugin selection
24
+ - 726491df: ZERO-3988: Add google pay integration
20
25
 
21
- ## 2.0.0-beta.9
26
+ ## 1.115.0
22
27
 
23
28
  ### Minor Changes
24
29
 
25
- - 0fe7711: ZERO-3387: Upgrade nextjs, eslint-config-next
30
+ - b59bed4d: ZERO-3878: Reintegrated similar products and removed localStorage checks and implemented props based showing of buttons
31
+ - b5f9d75c: ZERO-3873: Refactor payment redirection middlewares to properly forward all set-cookie headers from upstream responses
32
+ - cbcfdf4d: ZERO-3859: Haso payment gateway implmeneted
33
+ - 71882722: ZERO-3897: Add compress option to default Next.js configuration
34
+ - 7056203a: ZERO-3875: removed shared_tags through stripTags function for unused keys
26
35
 
27
- ## 2.0.0-beta.8
36
+ ## 1.114.0
28
37
 
29
38
  ### Minor Changes
30
39
 
31
- - 071d0f5: ZERO-3352: Resolve Single item size exceeds maxSize error and upgrade dependencies
40
+ - 65d3b862: ZERO-3054: Update headers in appFetch
41
+ - 43c182ee: ZERO-3054: Update Redis variable checks to conditionally include CACHE_SECRET
42
+ - eeb20bea: Revert "ZERO-3054: Refactor cache handler to use custom Redis handler and implement key hashing"
43
+ - fdd255ee: ZERO-3054: Refactor cache handler to use custom Redis handler and implement key hashing
32
44
 
33
- ## 2.0.0-beta.7
45
+ ## 1.113.0
34
46
 
35
- ## 2.0.0-beta.6
47
+ ## 1.112.0
36
48
 
37
49
  ### Minor Changes
38
50
 
39
- - 8f05f9b: ZERO-3250: Beta branch synchronized with Main branch
51
+ - 888fdec: ZERO-3792: Virtual Try On new features are implemented and also basket support implemented.
40
52
 
41
- ## 2.0.0-beta.5
53
+ ## 1.111.0
42
54
 
43
55
  ### Minor Changes
44
56
 
45
- - e791eab: ZERO-3133: Add fallbackReducer for handling missing plugin reducers
57
+ - c026300: ZERO-3833: fix masterpass rest conflicts
58
+ - b47b9d8: ZERO-3414: create masterpass-rest package
59
+
60
+ ## 1.110.0
61
+
62
+ ### Minor Changes
46
63
 
47
- ## 2.0.0-beta.4
64
+ - fc752c9: ZERO-3795: Remove unnecessary redirection logic from payment middleware
65
+ - 757af4a: ZERO-3783: Update image remote patterns for security compliance
48
66
 
49
- ## 2.0.0-beta.3
67
+ ## 1.109.0
50
68
 
51
69
  ### Minor Changes
52
70
 
53
- - 5536b80: ZERO-3104: Add optional headers parameter
71
+ - fcbbea79: ZERO-3648: Add virtual try-on feature with localization support
54
72
 
55
- ## 2.0.0-beta.2
73
+ ## 1.108.0
56
74
 
57
75
  ### Minor Changes
58
76
 
59
- - a006015: ZERO-3116: Add not-found page and update default middleware.
60
- - 999168d: ZERO-3104: Remove local cache handler from CacheHandler initialization
61
- - 1eeb3d8: ZERO-3116: Add not found page
62
- - 86a5a62: ZERO-3104: Add optional headers parameter to data fetching functions
63
- - dd69cc6: ZERO-3079: Modularize pre-order middleware
77
+ - d8883ce6: ZERO-3640: Refactor wallet completion handling to accept additional parameters; update related API calls
78
+ - 59ed7a7e: ZERO-3640: Add order number state and update FlowPayment component for wallet payment response handling
79
+ - 31a2d35a: ZERO-3640: Refactor checkout API call to include useFormData option; update FlowPayment component for improved error handling and code readability
80
+
81
+ ## 1.107.0
82
+
83
+ ### Minor Changes
84
+
85
+ - 4ca44c78: ZERO-3634: add register_consumer_card
86
+ - 28c7ea79: ZERO-3427: Refactor redirect utility to handle undefined URL and improve locale handling
87
+ - b6e5b624: ZERO-3257: Enhance locale middleware to redirect using existing or default locale and support 303 status for POST requests
88
+ - 5b500797: ZERO-3634: iyzico saved card
89
+
90
+ ## 1.106.0
91
+
92
+ ### Minor Changes
93
+
94
+ - 9dc7298: ZERO-3416: Refactor Accordion component to enhance props and improve styling flexibility
95
+ - 2d3f178: ZERO-3417: Enhance FileInput component with additional props for customization
96
+
97
+ ## 1.105.0
98
+
99
+ ### Minor Changes
100
+
101
+ - c39c700: ZERO-3420: Refactor Modal component
102
+ - d512ea2: ZERO-3656: update setLoyaltyData mutation to accept string type
103
+ - 3b255fe: ZERO-3629 :edit warnings in build
104
+
105
+ ## 1.104.0
106
+
107
+ ### Minor Changes
108
+
109
+ - 63774a6: ZERO-3351: Add commerce redirection ignore list functionality and related utility
110
+ - a2fbee6: ZERO-3651: Fix correct is Iframe property in contextListMiddleware
111
+ - 0de5573: ZERO-3418: Update remotePatterns hostname to allow all subdomains
112
+ - 5ad87ff: ZERO-3646: Refactor form submission API to handle form data and improve error responses
113
+
114
+ ## 1.103.0
115
+
116
+ ## 1.102.0
117
+
118
+ ### Minor Changes
119
+
120
+ - 6b949cb: ZERO-3615: Refactor product data handling and improve 404 error handling
121
+ - 9a3885b: ZERO-3660: skip catch-all not_found route in generate route script
122
+
123
+ ## 1.101.0
124
+
125
+ ### Minor Changes
126
+
127
+ - 4e863f7: ZERO-3654: add null check for resetMasterpassState in PaymentOptionResetMiddleware
128
+
129
+ ## 1.100.0
130
+
131
+ ### Minor Changes
132
+
133
+ - e57cd93: ZERO-3460: prevent installment loop on payment method switch
134
+ - 5f7edd6: ZERO-3571: Enhance Jest configuration by adding base directory resolution and module name mapping
135
+ - b00a90b: ZERO-3436: Preserve query params on redirect
136
+ - 26b2d0b: ZERO-3571: Remove test script execution from prebuild and simplify Jest module name mapping
137
+ - c51de38: ZERO-3637: Add action creators and RTK Query API endpoints to Redux store
138
+ - d1bb93a: ZERO-3460: fix installment request loop"
139
+
140
+ ## 1.99.0
141
+
142
+ ### Minor Changes
143
+
144
+ - cf90355: ZERO-3586_2: Enhance caching functionality by adding support for compressed data storage and retrieval, along with a new method for setting multiple key-value pairs.
145
+ - d58538b: ZERO-3638: Enhance RC pipeline: add fetch, merge, and pre-release setup with conditional commit
146
+ - 95a4cd1: ZERO-3631: add automatic route generation
147
+
148
+ ## 1.98.0
149
+
150
+ ### Minor Changes
151
+
152
+ - 67308f0: ZERO-3633: Revert IndexPage parameter from fetchCheckout request
153
+
154
+ ## 1.97.0
155
+
156
+ ### Minor Changes
157
+
158
+ - 0014305: ZERO-3629 :edit warnings in build
159
+
160
+ ## 1.96.0
161
+
162
+ ### Minor Changes
163
+
164
+ - af5c93a: ZERO-3617: Add pre-order middleware instruction file
165
+ - a420947: ZERO-3517: Fix optional chaining for rawData in error logging for category data handlers
166
+
167
+ ## 1.95.0
168
+
169
+ ### Minor Changes
170
+
171
+ - 35dfb8f: ZERO-3363: Refactor URL handling in checkout and redirection middlewares to use url.origin instead of process.env.NEXT_PUBLIC_URL
172
+ - 99b6e7b: ZERO-3421: Enhance Sentry error handling by adding network error detection logic and refining initialization options
173
+ - cbdb5c1: ZERO-3448: fix set cookie domain handling for subdomain locale strategy
174
+
175
+ ## 1.94.0
176
+
177
+ ### Minor Changes
178
+
179
+ - 6e6b0a9: ZERO-3422: Add pz-flow-payment package
180
+ - adf0eeb: ZERO-3597: Add copilot instruction files
181
+ - c806fad: ZERO-3422: Add Flow Payment plugin to the defined plugins list
182
+ - 0abde6b: ZERO-3422: Update fetch method to use dynamic request method in wallet complete redirection middleware
183
+ - 72ad7bb: ZERO-3422: Add Flow Payment to the list of available plugins
184
+ - e7cd3a5: ZERO-3435: Add Accept-Language to requestHeaders
185
+ - 17bfadc: ZERO-3275: Disable OpenTelemetry monitoring in production environment
186
+ - dfaceff: ZERO-3356: Add useLoyaltyAvailability hook and update checkout state management
187
+ - 86642cf: ZERO-3531: Add saveSampleProducts endpoint and update URLs in checkout
188
+ - 485e8ef: ZERO-3422: Refactor parameter handling in wallet complete redirection middleware to use forEach
189
+ - b434ac8: ZERO-3545: Update fetchCheckout API URL to include page parameter
190
+ - fee608d: ZERO-3422: Refactor body handling in wallet complete redirection middleware
191
+
192
+ ## 1.93.0
193
+
194
+ ### Minor Changes
195
+
196
+ - 185396f: ZERO-3569: Refactor logging in cache handler to use console_log instead of logger
197
+ - 0bdab12: ZERO-3569: Refactor cache handler to improve Redis connection management and logging
198
+ - 3e4aadc: ZERO-3569: Fix import statement for logger in cache handler
199
+
200
+ ## 1.92.0
201
+
202
+ ## 1.91.0
203
+
204
+ ### Minor Changes
205
+
206
+ - d8fad39: ZERO-3370: include plugins test to build stage
207
+ - 2552486: ZERO-3391: Add subdomain support to setLocale function
208
+ - f8e4cac: ZERO-3343: restrict root hostname to only locale subdomains
209
+ - 832bee3: ZERO-3343: add domain to cookie for subdomain locale strategy
210
+ - 28a59d4: ZERO-3400: refactor cookie domain logic using fallback host
211
+ - 8feabe9: ZERO-3343: add custom NextAuth options support
212
+ - bf354de: ZERO-3321: add babel compiler for akinon/next test
213
+ - 448adef: ZERO-3321: move csp test to akinon-next
214
+ - 6c3629c: ZERO-3321: fix jest tests in akinon-next for standalone projects
215
+ - 6bc260b: ZERO-3295: update default tailwind content list
216
+ - 943a239: ZERO-3370: add allowJs in akinon-next test tsconfig
217
+ - 068dc39: ZERO-3343: update get-root-hostname logic
218
+ - 942490f: ZERO-3295: move third party tailwind content list to akinon-next
219
+ - b6d5bda: ZERO-3343: update changeset config
220
+ - acf0320: ZERO-3321: remove babel config
221
+ - 387356b: ZERO-3323: Refactor locale filtering logic in URL matcher regex
222
+ - b2ee69b: ZERO-3321: delete unnecessary files
223
+ - 0cabbda: ZERO-3370: replace inline monorepo check with reusable utility
224
+
225
+ ## 1.90.0
226
+
227
+ ### Minor Changes
228
+
229
+ - e68e120: ZERO-3398: Add redirectUrlMiddleware to handle redirection based on checkout results
64
230
 
65
- ## 2.0.0-beta.1
231
+ ## 1.89.0
232
+
233
+ ## 1.88.0
234
+
235
+ ### Minor Changes
236
+
237
+ - c4f0568: ZERO-3293: Remove unnecessary pretty URL route check in Cache class method
238
+ - f3dcb1e: ZERO-3337 :Add support for cash register hook in middleware routing
239
+ - 8154859: ZERO-3337 :Add support for cash register pre-order hook in middleware
240
+
241
+ ## 1.87.0
242
+
243
+ ## 1.86.0
66
244
 
67
245
  ### Minor Changes
68
246
 
69
- - ZERO-3091: Upgrade Next.js to v15 and React to v19
247
+ - 6fc8ac5: ZERO-3229: Implement mini basket query for basket total quantity
248
+ - ef75c03: ZERO-3267: Update error-page component to use ROUTES for link navigation
249
+ - e4761d2: Refactor import statement for ROUTES in error-page component
250
+ - e2c6d42: ZERO-2935: Add @sentry/nextjs dependency to akinon-next and remove from projectzeronext
251
+ - 4d3deb4: ZERO-2935: sentry 8 upgrade
252
+ - c3f8d4a: ZERO-3274: Adjust button styles
253
+ - 9abd011: ZERO-3267: Refactor error handling in ErrorPage component to set error details in Sentry scope
254
+ - c3b2f3f: ZERO-3267: Enable sentry client errors and filter them by log type
255
+ - 70bc0ae: ZERO-3284: Set tracesSampleRate in Sentry configuration
256
+ - ac65ca9: ZERO-3269: Enhance locale handling by adding Subdomain strategy and updating related functions
257
+ - 0cb3ec0: ZERO-3281: Remove prebuild tests script from pz-prebuild
258
+ - 2d305aa: ZERO-2935: Update Sentry configuration: remove hideSourceMaps option and add it to withPzConfig
259
+ - 2f3588f: ZERO-3287: Add user session handling in authentication flow
260
+ - e5529cd: ZERO-3267: Update error-page component to use root path for links instead of ROUTES
70
261
 
71
- ## 2.0.0-beta.0
262
+ ## 1.85.0
263
+
264
+ ### Minor Changes
72
265
 
73
- ### Major Changes
266
+ - 4167dcd: ZERO-3253: Update Content-Security-Policy to include akinoncloud.com
267
+ - 0b1bd07: ZERO-3240: Remove unused preOrderMiddleware
74
268
 
75
- - be6c09d: ZERO-3114: Create beta version.
269
+ ## 1.84.0
270
+
271
+ ### Minor Changes
272
+
273
+ - 757ee53: ZERO-3207: Add SMS send & verify endpoints with state management
274
+ - c0c1962: ZERO-3258: Add new API endpoints for fetching Bukalemun image URL and bundle product data
275
+ - 0e05135: ZERO-3244: Encode URL search parameters
276
+
277
+ ## 1.83.0
278
+
279
+ ## 1.82.0
280
+
281
+ ### Minor Changes
282
+
283
+ - 2e0b7ff: ZERO-3226: Refactor checkoutApi to simplify request body structure by removing device_info parameter
284
+ - 778aabf: ZERO-3163: Add frontend ID header to authentication requests and forgot password mutation
285
+ - c0fef07: ZERO-3197: Refetch payment options after loyalty usage
286
+ - 2d2ab44: ZERO-3226: Add device_info param to WalletPaymentPage request
287
+ - 0200d56: ZERO-3163: Add frontendIds property to Settings interface
288
+ - 7d1b5af: ZERO-3206: Encode search parameters in product data URL
289
+ - aa05ed7: ZERO-3170: Add commerceRedirectionIgnoreList to settings and update URL redirection middleware
290
+
291
+ ## 1.81.0
292
+
293
+ ### Minor Changes
294
+
295
+ - fd4b74e: ZERO-3126: add reset checkout state query
296
+ - 4cc22c7: ZERO-3125: replace X-Frame-Options with CSP frame-ancestors
297
+ - 6a0a080: ZERO-3112: Update button
298
+
299
+ ## 1.80.0
300
+
301
+ ### Minor Changes
302
+
303
+ - 7ab9e2f: ZERO-3166: add tamara payment package
304
+
305
+ ## 1.79.0
306
+
307
+ ### Minor Changes
308
+
309
+ - 59fa21c: ZERO-3149: Add name-based mechanism for Redux middleware override
310
+
311
+ ## 1.78.0
312
+
313
+ ### Minor Changes
314
+
315
+ - e791eab: ZERO-3133: Add fallbackReducer for handling missing plugin reducers
316
+
317
+ ## 1.77.0
318
+
319
+ ### Minor Changes
320
+
321
+ - 999168d: ZERO-3104: Remove local cache handler from CacheHandler initialization
322
+ - 86a5a62: ZERO-3104: Add optional headers parameter to data fetching functions
323
+
324
+ ## 1.76.0
325
+
326
+ ### Minor Changes
327
+
328
+ - dd69cc6: ZERO-3079: Modularize pre-order middleware
76
329
 
77
330
  ## 1.75.0
78
331
 
package/api/auth.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { NextApiRequest, NextApiResponse } from 'next';
2
- import NextAuth, { Session, NextAuthOptions } from 'next-auth';
3
- import CredentialProvider from 'next-auth/providers/credentials';
1
+ import NextAuth, { Session, CredentialsSignin } from 'next-auth';
2
+ import Credentials from 'next-auth/providers/credentials';
4
3
  import { ROUTES } from 'routes';
5
4
  import { URLS, user } from '../data/urls';
6
5
  import Settings from 'settings';
@@ -9,9 +8,20 @@ import logger from '@akinon/next/utils/log';
9
8
  import { AuthError } from '../types';
10
9
  import getRootHostname from '../utils/get-root-hostname';
11
10
  import { LocaleUrlStrategy } from '../localization';
11
+ import { cookies, headers } from 'next/headers';
12
+
13
+ import type { NextAuthConfig } from 'next-auth';
14
+
15
+ class PzCredentialsError extends CredentialsSignin {
16
+ code = 'credentials';
17
+ constructor(errors: AuthError[]) {
18
+ super();
19
+ this.code = JSON.stringify(errors);
20
+ }
21
+ }
12
22
 
13
23
  async function getCurrentUser(sessionId: string, currency = '') {
14
- const headers = {
24
+ const reqHeaders = {
15
25
  'Content-Type': 'application/json',
16
26
  Cookie: `osessionid=${sessionId}`,
17
27
  'x-currency': currency
@@ -19,7 +29,7 @@ async function getCurrentUser(sessionId: string, currency = '') {
19
29
 
20
30
  const currentUser = await (
21
31
  await fetch(URLS.user.currentUser, {
22
- headers
32
+ headers: reqHeaders
23
33
  })
24
34
  ).json();
25
35
 
@@ -42,23 +52,18 @@ async function getCurrentUser(sessionId: string, currency = '') {
42
52
  };
43
53
  }
44
54
 
45
- type CustomNextAuthOptions = (
46
- req: NextApiRequest,
47
- res: NextApiResponse
48
- ) => Partial<NextAuthOptions>;
55
+ type CustomNextAuthOptions = () => Partial<NextAuthConfig>;
49
56
 
50
- const defaultNextAuthOptions = (
51
- req: NextApiRequest,
52
- res: NextApiResponse
53
- ): NextAuthOptions => {
57
+ const getDefaultAuthConfig = (): NextAuthConfig => {
54
58
  return {
55
59
  providers: [
56
- CredentialProvider({
60
+ Credentials({
57
61
  id: 'oauth',
58
62
  name: 'credentials',
59
63
  credentials: {},
60
64
  authorize: async (credentials) => {
61
- const sessionId = req.cookies['osessionid'];
65
+ const cookieStore = await cookies();
66
+ const sessionId = cookieStore.get('osessionid')?.value;
62
67
 
63
68
  if (!sessionId) {
64
69
  return null;
@@ -66,12 +71,12 @@ const defaultNextAuthOptions = (
66
71
 
67
72
  const currentUser = await getCurrentUser(
68
73
  sessionId,
69
- req.cookies['pz-currency'] ?? ''
74
+ cookieStore.get('pz-currency')?.value ?? ''
70
75
  );
71
76
  return currentUser;
72
77
  }
73
78
  }),
74
- CredentialProvider({
79
+ Credentials({
75
80
  id: 'default',
76
81
  name: 'credentials',
77
82
  credentials: {
@@ -86,49 +91,58 @@ const defaultNextAuthOptions = (
86
91
  captchaValidated: {}
87
92
  },
88
93
  authorize: async (credentials) => {
89
- const headers: HeadersInit = new Headers();
94
+ const cookieStore = await cookies();
95
+ const headerStore = await headers();
96
+
97
+ const reqHeaders: HeadersInit = new Headers();
90
98
  const language = Settings.localization.locales.find(
91
- (item) => item.value === credentials.locale
99
+ (item) => item.value === (credentials as any).locale
92
100
  ).apiValue;
93
- const userIp = req.headers['x-forwarded-for']?.toString() ?? '';
94
-
95
- headers.set('Content-Type', 'application/json');
96
- headers.set('cookie', `${req.headers.cookie}`);
97
- headers.set('Accept-Language', `${language}`);
98
- headers.set('x-currency', req.cookies['pz-currency'] ?? '');
99
- headers.set('x-forwarded-for', userIp);
100
- headers.set(
101
+ const userIp = headerStore.get('x-forwarded-for') ?? '';
102
+
103
+ reqHeaders.set('Content-Type', 'application/json');
104
+ reqHeaders.set('cookie', headerStore.get('cookie') ?? '');
105
+ reqHeaders.set('Accept-Language', `${language}`);
106
+ reqHeaders.set(
107
+ 'x-currency',
108
+ cookieStore.get('pz-currency')?.value ?? ''
109
+ );
110
+ reqHeaders.set('x-forwarded-for', userIp);
111
+ reqHeaders.set(
101
112
  'x-app-device',
102
- req.headers['x-app-device']?.toString() ?? ''
113
+ headerStore.get('x-app-device') ?? ''
103
114
  );
104
115
 
105
- headers.set('x-frontend-id', req.cookies['pz-frontend-id'] || '');
116
+ reqHeaders.set(
117
+ 'x-frontend-id',
118
+ cookieStore.get('pz-frontend-id')?.value || ''
119
+ );
106
120
 
107
121
  logger.debug('Trying to login/register', {
108
- formType: credentials.formType,
122
+ formType: (credentials as any).formType,
109
123
  userIp
110
124
  });
111
125
 
112
126
  const checkCurrentUser = await getCurrentUser(
113
- req.cookies['osessionid'] ?? '',
114
- req.cookies['pz-currency'] ?? ''
127
+ cookieStore.get('osessionid')?.value ?? '',
128
+ cookieStore.get('pz-currency')?.value ?? ''
115
129
  );
116
130
 
117
131
  if (checkCurrentUser?.pk) {
118
- const sessionCookie = headers
132
+ const sessionCookie = reqHeaders
119
133
  .get('cookie')
120
134
  ?.match(/osessionid=\w+/)?.[0]
121
135
  .replace(/osessionid=/, '');
122
136
  if (sessionCookie) {
123
- headers.set('cookie', sessionCookie);
137
+ reqHeaders.set('cookie', sessionCookie);
124
138
  }
125
139
  }
126
140
 
127
141
  const apiRequest = await fetch(
128
- `${Settings.commerceUrl}${user[credentials.formType]}`,
142
+ `${Settings.commerceUrl}${user[(credentials as any).formType]}`,
129
143
  {
130
144
  method: 'POST',
131
- headers,
145
+ headers: reqHeaders,
132
146
  body: JSON.stringify(credentials)
133
147
  }
134
148
  );
@@ -163,21 +177,25 @@ const defaultNextAuthOptions = (
163
177
  const { localeUrlStrategy } = Settings.localization;
164
178
 
165
179
  const fallbackHost =
166
- req.headers['x-forwarded-host']?.toString() ||
167
- req.headers.host?.toString();
180
+ headerStore.get('x-forwarded-host') ||
181
+ headerStore.get('host');
168
182
  const hostname =
169
183
  process.env.NEXT_PUBLIC_URL || `https://${fallbackHost}`;
170
184
  const rootHostname =
171
185
  localeUrlStrategy === LocaleUrlStrategy.Subdomain
172
186
  ? getRootHostname(hostname)
173
187
  : null;
174
- const domainOption = rootHostname ? `Domain=${rootHostname};` : '';
175
- const cookieOptions = `Path=/; HttpOnly; Secure; Max-Age=${maxAge}; ${domainOption}`;
176
188
 
177
- res.setHeader('Set-Cookie', [
178
- `osessionid=${sessionId}; ${cookieOptions}`,
179
- `sessionid=${sessionId}; ${cookieOptions}` // required to get 3D redirection form
180
- ]);
189
+ const cookieOptions = {
190
+ path: '/',
191
+ httpOnly: true,
192
+ secure: true,
193
+ maxAge,
194
+ ...(rootHostname ? { domain: rootHostname } : {})
195
+ };
196
+
197
+ cookieStore.set('osessionid', sessionId, cookieOptions);
198
+ cookieStore.set('sessionid', sessionId, cookieOptions);
181
199
  }
182
200
 
183
201
  if (!response.key) {
@@ -198,8 +216,8 @@ const defaultNextAuthOptions = (
198
216
  });
199
217
 
200
218
  logger.debug('Captcha required', {
201
- email: credentials.email,
202
- formType: credentials.formType
219
+ email: (credentials as any).email,
220
+ formType: (credentials as any).formType
203
221
  });
204
222
  } else if (apiRequest.status === 202) {
205
223
  errors.push({
@@ -218,13 +236,13 @@ const defaultNextAuthOptions = (
218
236
  }
219
237
 
220
238
  if (errors.length) {
221
- throw new Error(JSON.stringify(errors));
239
+ throw new PzCredentialsError(errors);
222
240
  }
223
241
  }
224
242
 
225
243
  const currentUser = await getCurrentUser(
226
244
  sessionId,
227
- req.cookies['pz-currency'] ?? ''
245
+ cookieStore.get('pz-currency')?.value ?? ''
228
246
  );
229
247
  return currentUser;
230
248
  }
@@ -238,18 +256,20 @@ const defaultNextAuthOptions = (
238
256
 
239
257
  return token;
240
258
  },
241
- async session({ session, user, token }) {
242
- session.user = token.user as Session['user'];
259
+ async session({ session, token }) {
260
+ session.user = token.user as any;
243
261
  return session;
244
262
  },
245
263
  async redirect({ url, baseUrl }: { url: string; baseUrl: string }) {
264
+ const headerStore = await headers();
246
265
  const pathname = url.startsWith('/') ? url : url.replace(baseUrl, '');
247
266
  const pathnameWithoutLocale = pathname.replace(
248
267
  urlLocaleMatcherRegex,
249
268
  ''
250
269
  );
251
270
 
252
- const localeResults = req.headers.referer
271
+ const localeResults = headerStore
272
+ .get('referer')
253
273
  ?.replace(baseUrl, '')
254
274
  ?.match(urlLocaleMatcherRegex);
255
275
 
@@ -260,11 +280,16 @@ const defaultNextAuthOptions = (
260
280
  signIn: () => {
261
281
  logger.debug('Successfully signed in');
262
282
  },
263
- signOut: () => {
264
- res.setHeader('Set-Cookie', [
265
- `osessionid=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
266
- `sessionid=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`
267
- ]);
283
+ signOut: async () => {
284
+ const cookieStore = await cookies();
285
+ cookieStore.set('osessionid', '', {
286
+ path: '/',
287
+ maxAge: 0
288
+ });
289
+ cookieStore.set('sessionid', '', {
290
+ path: '/',
291
+ maxAge: 0
292
+ });
268
293
  logger.debug('Successfully signed out');
269
294
  }
270
295
  },
@@ -275,36 +300,33 @@ const defaultNextAuthOptions = (
275
300
  };
276
301
  };
277
302
 
278
- const Auth = (
279
- req: NextApiRequest,
280
- res: NextApiResponse,
281
- customOptions?: CustomNextAuthOptions
282
- ) => {
283
- const baseOptions = defaultNextAuthOptions(req, res);
284
- const customOptionsResult = customOptions ? customOptions(req, res) : {};
285
-
286
- const mergedOptions = {
287
- ...baseOptions,
288
- ...customOptionsResult,
303
+ export const createAuth = (customOptions?: CustomNextAuthOptions) => {
304
+ const baseConfig = getDefaultAuthConfig();
305
+ const customConfig = customOptions ? customOptions() : {};
306
+
307
+ const mergedConfig: NextAuthConfig = {
308
+ trustHost: true,
309
+ ...baseConfig,
310
+ ...customConfig,
289
311
  providers: [
290
- ...baseOptions.providers,
291
- ...(customOptionsResult.providers || [])
312
+ ...baseConfig.providers,
313
+ ...(customConfig.providers || [])
292
314
  ],
293
315
  callbacks: {
294
- ...baseOptions.callbacks,
295
- ...customOptionsResult.callbacks
316
+ ...baseConfig.callbacks,
317
+ ...customConfig.callbacks
296
318
  },
297
319
  events: {
298
- ...baseOptions.events,
299
- ...customOptionsResult.events
320
+ ...baseConfig.events,
321
+ ...customConfig.events
300
322
  },
301
323
  pages: {
302
- ...baseOptions.pages,
303
- ...customOptionsResult.pages
324
+ ...baseConfig.pages,
325
+ ...customConfig.pages
304
326
  }
305
327
  };
306
328
 
307
- return NextAuth(req, res, mergedOptions);
329
+ return NextAuth(mergedConfig);
308
330
  };
309
331
 
310
- export default Auth;
332
+ export default createAuth;