@preprio/prepr-nextjs 1.3.1 → 2.0.0-alpha.10

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 (58) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +532 -112
  3. package/dist/chunk-E7ATRJ2F.js +2 -0
  4. package/dist/chunk-E7ATRJ2F.js.map +1 -0
  5. package/dist/chunk-LVXDK2EY.js +2 -0
  6. package/dist/chunk-LVXDK2EY.js.map +1 -0
  7. package/dist/index.css +1 -0
  8. package/dist/metafile-cjs.json +1 -0
  9. package/dist/metafile-esm.json +1 -0
  10. package/dist/middleware/index.cjs +2 -0
  11. package/dist/middleware/index.cjs.map +1 -0
  12. package/dist/middleware/index.d.cts +26 -0
  13. package/dist/middleware/index.d.ts +26 -0
  14. package/dist/middleware/index.js +2 -0
  15. package/dist/middleware/index.js.map +1 -0
  16. package/dist/react/index.cjs +3 -0
  17. package/dist/react/index.cjs.map +1 -0
  18. package/dist/react/index.d.cts +43 -0
  19. package/dist/react/index.d.ts +43 -0
  20. package/dist/react/index.js +3 -0
  21. package/dist/react/index.js.map +1 -0
  22. package/dist/server/index.cjs +7 -0
  23. package/dist/server/index.cjs.map +1 -0
  24. package/dist/server/index.d.cts +62 -0
  25. package/dist/server/index.d.ts +62 -0
  26. package/dist/server/index.js +7 -0
  27. package/dist/server/index.js.map +1 -0
  28. package/dist/types/index.cjs +2 -0
  29. package/dist/types/index.cjs.map +1 -0
  30. package/dist/types/index.d.cts +34 -0
  31. package/dist/types/index.d.ts +34 -0
  32. package/dist/types/index.js +2 -0
  33. package/dist/types/index.js.map +1 -0
  34. package/dist/utils/index.cjs +2 -0
  35. package/dist/utils/index.cjs.map +1 -0
  36. package/dist/utils/index.d.cts +164 -0
  37. package/dist/utils/index.d.ts +164 -0
  38. package/dist/utils/index.js +2 -0
  39. package/dist/utils/index.js.map +1 -0
  40. package/package.json +104 -59
  41. package/dist/chunk-IQXHJV5O.mjs +0 -25
  42. package/dist/chunk-IQXHJV5O.mjs.map +0 -1
  43. package/dist/components.css +0 -430
  44. package/dist/components.css.map +0 -1
  45. package/dist/components.d.mts +0 -10
  46. package/dist/components.d.ts +0 -10
  47. package/dist/components.js +0 -415
  48. package/dist/components.js.map +0 -1
  49. package/dist/components.mjs +0 -388
  50. package/dist/components.mjs.map +0 -1
  51. package/dist/index.d.mts +0 -45
  52. package/dist/index.d.ts +0 -45
  53. package/dist/index.js +0 -325
  54. package/dist/index.js.map +0 -1
  55. package/dist/index.mjs +0 -279
  56. package/dist/index.mjs.map +0 -1
  57. package/dist/types-DmITW6Tn.d.mts +0 -6
  58. package/dist/types-DmITW6Tn.d.ts +0 -6
package/README.md CHANGED
@@ -1,165 +1,585 @@
1
- # The Prepr Next.js package
1
+ # Prepr Next.js Package
2
2
 
3
- ## Getting Started
4
- <hr>
5
- The Prepr Next.js package offers some helper functions and the Adaptive Preview Bar component for an
6
- easier personalization & A/B testing implementation in your Next.js project.
3
+ A powerful TypeScript library that provides preview functionality, visual editing capabilities, and A/B testing for [Prepr CMS](https://prepr.io) integrated with Next.js applications.
7
4
 
8
- ## Installation
9
- <hr>
10
- To install the Prepr Next.js package, run the following command:
5
+ ## ⚡ Quick Start
11
6
 
12
7
  ```bash
8
+ # Install the package
13
9
  npm install @preprio/prepr-nextjs
10
+ # or
11
+ pnpm add @preprio/prepr-nextjs
14
12
  ```
15
13
 
16
- Next, add the `PREPR_ENV` variable to the `.env` file. You can enable the *Adaptive Preview Bar* for a staging environment by setting the value to `preview`.
14
+ Add environment variables to your `.env`:
17
15
 
18
16
  ```bash
17
+ PREPR_GRAPHQL_URL=https://graphql.prepr.io/{YOUR_ACCESS_TOKEN}
19
18
  PREPR_ENV=preview
20
19
  ```
21
20
 
22
- When you're launching your project to production, then set the `PREPR_ENV` environment variable to `production`. This way, the *Adaptive Preview Bar* doesn't get displayed on a live web app.
21
+ Set up middleware in `middleware.ts`:
23
22
 
24
- Next, implement the `PreprMiddleware` function. Go to your `middleware.js` or the `middleware.ts`
25
- file. If you don't have this file, you can create it in the root of your project.
23
+ ```typescript
24
+ import type { NextRequest } from 'next/server'
25
+ import createPreprMiddleware from '@preprio/prepr-nextjs/middleware'
26
26
 
27
- Then add the following code to the `middleware.ts` file:
28
- ```javascript
27
+ export function middleware(request: NextRequest) {
28
+ return createPreprMiddleware(request, { preview: true })
29
+ }
30
+ ```
31
+
32
+ Add preview bar to your layout:
33
+
34
+ ```typescript
35
+ import { getPreviewBarProps } from '@preprio/prepr-nextjs/server'
36
+ import { PreprPreviewBar, PreprPreviewBarProvider } from '@preprio/prepr-nextjs/react'
37
+ import '@preprio/prepr-nextjs/index.css'
38
+
39
+ export default async function RootLayout({ children }: { children: React.ReactNode }) {
40
+ const previewBarProps = await getPreviewBarProps(process.env.PREPR_GRAPHQL_URL!)
41
+
42
+ return (
43
+ <html>
44
+ <body>
45
+ <PreprPreviewBarProvider props={previewBarProps}>
46
+ <PreprPreviewBar />
47
+ {children}
48
+ </PreprPreviewBarProvider>
49
+ </body>
50
+ </html>
51
+ )
52
+ }
53
+ ```
54
+
55
+ ## 📋 Prerequisites
56
+
57
+ Before installing, ensure you have:
58
+
59
+ - **Next.js 13.0.0 or later** (supports App Router)
60
+ - **React 17.0.0 or later** (React 18+ recommended)
61
+ - **Node.js 16.0.0 or later**
62
+ - **A Prepr account**
63
+ - **Prepr GraphQL URL** (found in Settings → Access tokens)
64
+
65
+ ### Prepr Account Setup
66
+
67
+ 1. **Create a Prepr account** at [prepr.io](https://prepr.io)
68
+ 2. **Get your GraphQL URL**:
69
+ - Go to Settings → Access tokens
70
+ - Find your GraphQL Preview access token
71
+ - Copy the full GraphQL URL (e.g., `https://graphql.prepr.io/e6f7a0521f11e5149ce65b0e9f372ced2dfc923490890e7f225da1db84cxxxxx`)
72
+ - The URL format is always `https://graphql.prepr.io/{YOUR_ACCESS_TOKEN}`
73
+ 3. **Enable edit mode** (for preview bar):
74
+ - Open your GraphQL Preview access token
75
+ - Check "Enable edit mode"
76
+ - Save the token
77
+
78
+ ## 🔧 Installation & Setup
79
+
80
+ ### 1. Install the Package
81
+
82
+ ```bash
83
+ npm install @preprio/prepr-nextjs
84
+ # or
85
+ pnpm add @preprio/prepr-nextjs
86
+ # or
87
+ yarn add @preprio/prepr-nextjs
88
+ ```
89
+
90
+ ### 2. Environment Configuration
91
+
92
+ Create or update your `.env` file:
93
+
94
+ ```bash
95
+ # Required: Your Prepr GraphQL endpoint
96
+ PREPR_GRAPHQL_URL=https://graphql.prepr.io/{YOUR_ACCESS_TOKEN}
97
+
98
+ # Required: Environment mode
99
+ PREPR_ENV=preview # Use 'preview' for staging/development
100
+ # PREPR_ENV=production # Use 'production' for live sites
101
+
102
+ # Optional: Enable debug logging (development only)
103
+ # PREPR_DEBUG=true
104
+ ```
105
+
106
+ > **Important**: Replace `{YOUR_ACCESS_TOKEN}` with your actual Prepr access token from Settings → Access tokens.
107
+
108
+ ### 3. Middleware Setup
109
+
110
+ The middleware handles personalization headers, customer ID tracking, and preview mode functionality.
111
+
112
+ #### TypeScript Setup
113
+
114
+ Create or update `middleware.ts` in your project root:
115
+
116
+ ```typescript
29
117
  import type { NextRequest } from 'next/server'
30
- import { PreprMiddleware } from '@preprio/prepr-nextjs'
118
+ import createPreprMiddleware from '@preprio/prepr-nextjs/middleware'
31
119
 
32
120
  export function middleware(request: NextRequest) {
33
- return PreprMiddleware(request)
121
+ return createPreprMiddleware(request, {
122
+ preview: process.env.PREPR_ENV === 'preview'
123
+ })
124
+ }
125
+
126
+ export const config = {
127
+ matcher: [
128
+ /*
129
+ * Match all request paths except for the ones starting with:
130
+ * - api (API routes)
131
+ * - _next/static (static files)
132
+ * - _next/image (image optimization files)
133
+ * - favicon.ico (favicon file)
134
+ */
135
+ '/((?!api|_next/static|_next/image|favicon.ico).*)',
136
+ ],
34
137
  }
35
138
  ```
36
139
 
37
- Or add the following code to the `middleware.js` file:
140
+ #### JavaScript Setup
141
+
142
+ Create or update `middleware.js` in your project root:
143
+
38
144
  ```javascript
39
- import { PreprMiddleware } from '@preprio/prepr-nextjs'
145
+ import createPreprMiddleware from '@preprio/prepr-nextjs/middleware'
146
+
147
+ export async function middleware(request) {
148
+ return createPreprMiddleware(request, {
149
+ preview: process.env.PREPR_ENV === 'preview'
150
+ })
151
+ }
40
152
 
41
- export function middleware(request) {
42
- return PreprMiddleware(request)
153
+ export const config = {
154
+ matcher: [
155
+ '/((?!api|_next/static|_next/image|favicon.ico).*)',
156
+ ],
43
157
  }
44
158
  ```
45
159
 
46
- ### Middleware functionality
47
- The `PreprMiddleware` accepts a request and optional response property and returns a `NextRequest` object.
48
- This is done so you are able to chain your own middleware to it.
160
+ #### Chaining with Existing Middleware
49
161
 
50
- The `PreprMiddleware` function checks every request if the `__prepr_uid` cookie is set. If it isn't, the function generates a new UUID and sets it as a cookie. Then it returns a `Prepr-Customer-Id` header with the value of the `__prepr_uid` cookie to simplify your personalization and A/B testing implementation.
162
+ ##### Basic Chaining Pattern
51
163
 
52
- If the `PREPR_ENV` environment variable is set to `preview`, the `PreprMiddleware` function also checks for searchParams `segments` and `a-b-testing` in the URL.
53
- If these searchParams are set, the PreprMiddleware sets the `Prepr-Segments` and `Prepr-AB-Testing` headers with the values of the searchParams, and stores its value in a cookie.
164
+ ```typescript
165
+ import type { NextRequest, NextResponse } from 'next/server'
166
+ import createPreprMiddleware from '@preprio/prepr-nextjs/middleware'
54
167
 
55
- ## Usage
56
- To set your API request headers to query adaptive content or A/B testing content, you can call the `getPreprHeaders()` helper function. It returns an array of headers that you can spread in your fetch call.
57
- See the example code below in the `page.tsx` file.
168
+ export function middleware(request: NextRequest) {
169
+ // Start with your existing middleware
170
+ let response = NextResponse.next()
171
+
172
+ // Add your custom logic
173
+ if (request.nextUrl.pathname.startsWith('/admin')) {
174
+ response.headers.set('x-admin-route', 'true')
175
+ }
176
+
177
+ // Chain with Prepr middleware
178
+ return createPreprMiddleware(request, response, {
179
+ preview: process.env.PREPR_ENV === 'preview'
180
+ })
181
+ }
182
+ ```
58
183
 
59
- ```javascript
60
- import { getClient } from '@/lib/client'
61
- import { GetPageBySlugDocument, GetPageBySlugQuery } from '@/gql/graphql'
62
- import { getPreprHeaders } from '@preprio/prepr-nextjs'
63
-
64
- const getData = async () => {
65
- // Fetching the data using Apollo Client
66
- const {data} = await getClient().query < GetPageBySlugQuery > ({
67
- query: GetPageBySlugDocument,
68
- variables: {
69
- slug: '/',
70
- },
71
- context: {
72
- // Call the getPreprHeaders function to get the appropriate headers
73
- headers: getPreprHeaders(),
74
- },
75
- fetchPolicy: 'no-cache',
76
- })
184
+ ##### With next-intl Integration
185
+
186
+ ```typescript
187
+ import type { NextRequest } from 'next/server'
188
+ import createIntlMiddleware from 'next-intl/middleware'
189
+ import createPreprMiddleware from '@preprio/prepr-nextjs/middleware'
190
+
191
+ const intlMiddleware = createIntlMiddleware({
192
+ locales: ['en', 'de', 'fr'],
193
+ defaultLocale: 'en'
194
+ })
195
+
196
+ export function middleware(request: NextRequest) {
197
+ // First run internationalization middleware
198
+ const intlResponse = intlMiddleware(request)
199
+
200
+ // If next-intl returns a redirect, return it immediately
201
+ if (intlResponse.status >= 300 && intlResponse.status < 400) {
202
+ return intlResponse
203
+ }
204
+
205
+ // Otherwise, chain with Prepr middleware
206
+ return createPreprMiddleware(request, intlResponse, {
207
+ preview: process.env.PREPR_ENV === 'preview'
208
+ })
209
+ }
210
+
211
+ export const config = {
212
+ matcher: [
213
+ '/((?!api|_next/static|_next/image|favicon.ico).*)',
214
+ ],
77
215
  }
78
216
  ```
79
- See the JavaScript example code below in the `page.js`file.
80
217
 
81
- ```javascript
218
+ ##### Advanced Chaining with Multiple Middlewares
219
+
220
+ ```typescript
221
+ import type { NextRequest, NextResponse } from 'next/server'
222
+ import createPreprMiddleware from '@preprio/prepr-nextjs/middleware'
223
+ import { authMiddleware } from '@/lib/auth'
224
+ import { rateLimitMiddleware } from '@/lib/rate-limit'
225
+
226
+ export function middleware(request: NextRequest) {
227
+ let response = NextResponse.next()
228
+
229
+ // 1. Rate limiting
230
+ response = rateLimitMiddleware(request, response)
231
+
232
+ // 2. Authentication (if needed)
233
+ if (request.nextUrl.pathname.startsWith('/dashboard')) {
234
+ response = authMiddleware(request, response)
235
+ }
236
+
237
+ // 3. Custom headers
238
+ response.headers.set('x-custom-header', 'my-value')
239
+
240
+ // 4. Finally, Prepr middleware
241
+ return createPreprMiddleware(request, response, {
242
+ preview: process.env.PREPR_ENV === 'preview'
243
+ })
244
+ }
245
+ ```
246
+
247
+ ##### Conditional Chaining
248
+
249
+ ```typescript
250
+ import type { NextRequest, NextResponse } from 'next/server'
251
+ import createPreprMiddleware from '@preprio/prepr-nextjs/middleware'
252
+
253
+ export function middleware(request: NextRequest) {
254
+ const { pathname } = request.nextUrl
255
+
256
+ // Skip Prepr middleware for API routes
257
+ if (pathname.startsWith('/api/')) {
258
+ return NextResponse.next()
259
+ }
260
+
261
+ // Apply different logic based on route
262
+ let response = NextResponse.next()
263
+
264
+ if (pathname.startsWith('/blog')) {
265
+ response.headers.set('x-content-type', 'blog')
266
+ } else if (pathname.startsWith('/product')) {
267
+ response.headers.set('x-content-type', 'product')
268
+ }
269
+
270
+ // Always apply Prepr middleware for content routes
271
+ return createPreprMiddleware(request, response, {
272
+ preview: process.env.PREPR_ENV === 'preview'
273
+ })
274
+ }
275
+ ```
276
+
277
+ ### 4. Layout Integration
278
+
279
+ #### App Router (Next.js 13+)
280
+
281
+ Update your `app/layout.tsx`:
282
+
283
+ ```typescript
284
+ import { getPreviewBarProps } from '@preprio/prepr-nextjs/server'
285
+ import {
286
+ PreprPreviewBar,
287
+ PreprPreviewBarProvider
288
+ } from '@preprio/prepr-nextjs/react'
289
+ import '@preprio/prepr-nextjs/index.css'
290
+
291
+ export default async function RootLayout({
292
+ children,
293
+ }: {
294
+ children: React.ReactNode
295
+ }) {
296
+ const previewBarProps = await getPreviewBarProps(process.env.PREPR_GRAPHQL_URL!)
297
+
298
+ return (
299
+ <html lang="en">
300
+ <body>
301
+ <PreprPreviewBarProvider props={previewBarProps}>
302
+ <PreprPreviewBar />
303
+ {children}
304
+ </PreprPreviewBarProvider>
305
+ </body>
306
+ </html>
307
+ )
308
+ }
309
+ ```
310
+
311
+ ### 5. API Integration
312
+
313
+ Use the `getPreprHeaders()` helper function in your data fetching to enable personalization and A/B testing:
314
+
315
+ #### With Apollo Client
316
+
317
+ ```typescript
82
318
  import { getClient } from '@/lib/client'
83
- import { GetPageBySlug } from '@/queries/get-page-by-slug';
84
- import { getPreprHeaders } from '@preprio/prepr-nextjs'
85
-
86
- const getData = async () => {
87
- // Fetching the data using Apollo Client
88
- const { data } = await client.query({
89
- query: GetPageBySlug,
90
- variables: {
91
- slug: '/',
92
- },
319
+ import { GetPageBySlugDocument } from '@/gql/graphql'
320
+ import { getPreprHeaders } from '@preprio/prepr-nextjs/server'
321
+
322
+ const getData = async (slug: string) => {
323
+ const { data } = await getClient().query({
324
+ query: GetPageBySlugDocument,
325
+ variables: { slug },
93
326
  context: {
94
- // Call the getPreprHeaders function to get the appropriate headers
95
- headers: getPreprHeaders(),
96
- },
97
- fetchPolicy: 'no-cache',
98
- })
99
- return data;
327
+ headers: await getPreprHeaders(),
328
+ },
329
+ fetchPolicy: 'no-cache',
330
+ })
331
+ return data
100
332
  }
101
333
  ```
102
334
 
103
- ### Installing the Adaptive Preview Bar component
335
+ #### With Fetch API
104
336
 
105
- The preview bar component fetches all segments from the Prepr API. So, you need to give it access to do this as follows:
337
+ ```typescript
338
+ import { getPreprHeaders } from '@preprio/prepr-nextjs/server'
106
339
 
107
- 1. In your Prepr environment, go to the **Settings → Access tokens** page to view all the access tokens.
108
- 2. Click the *GraphQL Preview* access token to open it and tick the **Enable edit mode** checkbox and click the **Save** button.
340
+ const getData = async (slug: string) => {
341
+ const headers = await getPreprHeaders()
342
+
343
+ const response = await fetch(process.env.PREPR_GRAPHQL_URL!, {
344
+ method: 'POST',
345
+ headers: {
346
+ 'Content-Type': 'application/json',
347
+ ...headers,
348
+ },
349
+ body: JSON.stringify({
350
+ query: `
351
+ query GetPageBySlug($slug: String!) {
352
+ Page(slug: $slug) {
353
+ title
354
+ content
355
+ }
356
+ }
357
+ `,
358
+ variables: { slug },
359
+ }),
360
+ })
361
+
362
+ return response.json()
363
+ }
364
+ ```
109
365
 
110
- ![Preview access token](https://assets-site.prepr.io/229kaekn7m96//preview-access-token-enable-edit-mode.png)
366
+ ## 🎛️ API Reference
111
367
 
112
- To implement the *Adaptive Preview Bar* component, navigate to your root layout file, this is usually `layout.tsx`.
368
+ ### Server Functions
113
369
 
114
- Then add the following code to the `layout.tsx` file:
370
+ #### `getPreprHeaders()`
371
+ Returns all Prepr headers for API requests.
115
372
 
116
- ```javascript
117
- // Helper function to get all the props for the PreviewBar component (this needs a server component)
118
- import { getPreviewBarProps } from '@preprio/prepr-nextjs'
119
- // Import the PreviewBar component
120
- import { PreprPreviewBar } from '@preprio/prepr-nextjs/components'
121
- // Import the PreviewBar CSS
122
- import '@preprio/prepr-nextjs/dist/components.css'
123
-
124
-
125
- export default async function RootLayout({children}: {children: React.ReactNode}) {
126
- // Get the props for the PreviewBar component, pass the access token as an argument
127
- const previewBarProps = await getPreviewBarProps(process.env.PREPR_GRAPHQL_URL!)
128
-
129
- return (
130
- <html>
131
- <head>
132
- {/*...*/}
133
- </head>
134
- <body>
135
- {/* Render the PreviewBar component and spread the previewBarProps */}
136
- <PreprPreviewBar {...previewBarProps} />
137
- {children}
138
- </body>
139
- </html>
140
- )
373
+ ```typescript
374
+ import { getPreprHeaders } from '@preprio/prepr-nextjs/server'
375
+
376
+ const headers = await getPreprHeaders()
377
+ // Returns: { 'prepr-customer-id': 'uuid', 'Prepr-Segments': 'segment-id', ... }
378
+ ```
379
+
380
+ #### `getPreprUUID()`
381
+ Returns the current customer ID from headers.
382
+
383
+ ```typescript
384
+ import { getPreprUUID } from '@preprio/prepr-nextjs/server'
385
+
386
+ const customerId = await getPreprUUID()
387
+ // Returns: 'uuid-string' or null
388
+ ```
389
+
390
+ #### `getActiveSegment()`
391
+ Returns the currently active segment.
392
+
393
+ ```typescript
394
+ import { getActiveSegment } from '@preprio/prepr-nextjs/server'
395
+
396
+ const segment = await getActiveSegment()
397
+ // Returns: 'segment-id' or null
398
+ ```
399
+
400
+ #### `getActiveVariant()`
401
+ Returns the currently active A/B testing variant.
402
+
403
+ ```typescript
404
+ import { getActiveVariant } from '@preprio/prepr-nextjs/server'
405
+
406
+ const variant = await getActiveVariant()
407
+ // Returns: 'A' | 'B' | null
408
+ ```
409
+
410
+ #### `getPreviewBarProps()`
411
+ Fetches all necessary props for the preview bar component.
412
+
413
+ ```typescript
414
+ import { getPreviewBarProps } from '@preprio/prepr-nextjs/server'
415
+
416
+ const props = await getPreviewBarProps(process.env.PREPR_GRAPHQL_URL!)
417
+ // Returns: { activeSegment, activeVariant, data }
418
+ ```
419
+
420
+ #### `validatePreprToken()`
421
+ Validates a Prepr GraphQL URL format.
422
+
423
+ ```typescript
424
+ import { validatePreprToken } from '@preprio/prepr-nextjs/server'
425
+
426
+ const result = validatePreprToken('https://graphql.prepr.io/YOUR_ACCESS_TOKEN')
427
+ // Returns: { valid: boolean, error?: string }
428
+ ```
429
+
430
+ #### `isPreviewMode()`
431
+ Checks if the current environment is in preview mode.
432
+
433
+ ```typescript
434
+ import { isPreviewMode } from '@preprio/prepr-nextjs/server'
435
+
436
+ const isPreview = isPreviewMode()
437
+ // Returns: boolean
438
+ ```
439
+
440
+ ### React Components
441
+
442
+ #### `PreprPreviewBarProvider`
443
+ Context provider that wraps your app with preview bar functionality.
444
+
445
+ ```typescript
446
+ import { PreprPreviewBarProvider } from '@preprio/prepr-nextjs/react'
447
+
448
+ <PreprPreviewBarProvider props={previewBarProps}>
449
+ {children}
450
+ </PreprPreviewBarProvider>
451
+ ```
452
+
453
+ #### `PreprPreviewBar`
454
+ The main preview bar component.
455
+
456
+ ```typescript
457
+ import { PreprPreviewBar } from '@preprio/prepr-nextjs/react'
458
+
459
+ <PreprPreviewBar />
460
+ ```
461
+
462
+ ## 🔧 Configuration Options
463
+
464
+ ### Environment Variables
465
+
466
+ | Variable | Required | Default | Description |
467
+ |----------|----------|---------|-------------|
468
+ | `PREPR_GRAPHQL_URL` | Yes | - | Your Prepr GraphQL endpoint URL |
469
+ | `PREPR_ENV` | Yes | - | Environment mode (`preview` or `production`) |
470
+
471
+ ### Middleware Options
472
+
473
+ ```typescript
474
+ // Simple usage (creates new NextResponse)
475
+ createPreprMiddleware(request, {
476
+ preview: boolean // Enable preview mode functionality
477
+ })
478
+
479
+ // Chaining usage (uses existing NextResponse)
480
+ createPreprMiddleware(request, response, {
481
+ preview: boolean // Enable preview mode functionality
482
+ })
483
+ ```
484
+
485
+ ### Preview Bar Options
486
+
487
+ ```typescript
488
+ <PreprPreviewBarProvider
489
+ props={previewBarProps}
490
+ options={{
491
+ debug: true // Enable debug logging
492
+ }}
493
+ >
494
+ ```
495
+
496
+ ## 🚨 Troubleshooting
497
+
498
+ ### Common Issues
499
+
500
+ #### Preview Bar Not Showing
501
+ - **Check environment**: Ensure `PREPR_ENV=preview` is set
502
+ - **Verify GraphQL URL**: Make sure `PREPR_GRAPHQL_URL` is correct and follows the format `https://graphql.prepr.io/YOUR_ACCESS_TOKEN`
503
+ - **Check token permissions**: Ensure "Enable edit mode" is checked in Prepr
504
+
505
+ #### Headers Not Working
506
+ - **Middleware setup**: Verify middleware is properly configured
507
+ - **API calls**: Ensure you're using `getPreprHeaders()` in your API calls
508
+ - **Environment**: Check that environment variables are loaded
509
+
510
+ #### TypeScript Errors
511
+ - **Version compatibility**: Ensure you're using compatible versions of Next.js and React
512
+ - **Type imports**: Import types from `@preprio/prepr-nextjs/types`
513
+
514
+ #### Build Issues
515
+ - **CSS imports**: Make sure to import the CSS file in your layout
516
+ - **Server components**: Ensure server functions are only called in server components
517
+
518
+ ### Error Handling
519
+
520
+ The package includes comprehensive error handling:
521
+
522
+ ```typescript
523
+ import { PreprError } from '@preprio/prepr-nextjs/server'
524
+
525
+ try {
526
+ const segments = await getPreprEnvironmentSegments(process.env.PREPR_GRAPHQL_URL!)
527
+ } catch (error) {
528
+ if (error instanceof PreprError) {
529
+ console.log('Error code:', error.code)
530
+ console.log('Context:', error.context)
531
+ }
141
532
  }
142
533
  ```
143
534
 
144
- Now the *Adaptive Preview Bar* is rendered on every page of your website. This component shows the segments in a dropdown list and a switch for A and B variants for an A/B test. If you have added the `getPreprHeaders()` function
145
- to your API calls it automatically updates the segments and A/B testing variants when you select a new segment or variant.
535
+ ### Debug Mode
536
+
537
+ Enable debug logging in development:
538
+
539
+ ```typescript
540
+ <PreprPreviewBarProvider
541
+ props={previewBarProps}
542
+ options={{ debug: true }}
543
+ >
544
+ ```
545
+
546
+ ## 📊 How It Works
547
+
548
+ ### Middleware Functionality
549
+
550
+ The middleware automatically:
551
+ 1. **Generates customer IDs**: Creates unique visitor identifiers
552
+ 2. **Tracks UTM parameters**: Captures marketing campaign data
553
+ 3. **Manages segments**: Handles audience segmentation
554
+ 4. **Processes A/B tests**: Manages variant assignments
555
+ 5. **Sets headers**: Adds necessary headers for API calls
556
+
557
+ ### Preview Bar Features
558
+
559
+ The preview bar provides:
560
+ - **Segment selection**: Switch between different audience segments
561
+ - **A/B testing**: Toggle between variants A and B
562
+ - **Edit mode**: Visual content editing capabilities
563
+ - **Reset functionality**: Clear personalization settings
564
+
565
+ ### Visual Editing
146
566
 
147
- ### Helper functions
567
+ When edit mode is enabled, the package:
568
+ 1. **Scans content**: Identifies editable content using Stega encoding
569
+ 2. **Highlights elements**: Shows proximity-based highlighting
570
+ 3. **Provides overlays**: Click-to-edit functionality
571
+ 4. **Syncs with Prepr**: Direct integration with Prepr's editing interface
148
572
 
149
- #### getPreprUUID()
150
- The `getPreprUUID()` function will return the value of the `__prepr_uid` cookie. This can be useful if you want to store the `__prepr_uid` in a cookie or local storage.
573
+ ## 🔄 Upgrading from v1 to v2
151
574
 
152
- #### getActiveSegment()
153
- Returns the active segment from the `Prepr-Segments` header.
575
+ If you're upgrading from v1, please follow the [Upgrade Guide](./UPGRADE_GUIDE.md) for detailed migration instructions.
154
576
 
155
- #### getActiveVariant()
156
- Returns the active variant from the `Prepr-ABTesting` header.
577
+ ## 📜 License
157
578
 
158
- #### getPreviewHeaders()
159
- Helper function to only get the preview headers.
579
+ MIT License - see the [LICENSE](./LICENSE) file for details.
160
580
 
161
- #### getPreprHeaders()
162
- Helper function that will either return the customer id header or the preview headers depending on the `PREPR_ENV` environment variable.
581
+ ## 🆘 Support
163
582
 
164
- #### getPreviewBarProps()
165
- Helper function to get the props for the PreviewBar component. Will return the segments and A/B testing variants aswell as an aray of all the segments.
583
+ - **Documentation**: [Prepr Documentation](https://docs.prepr.io)
584
+ - **Issues**: [GitHub Issues](https://github.com/preprio/prepr-nextjs/issues)
585
+ - **Community**: [Prepr Community](https://community.prepr.io)