create-tigra 2.3.0 → 2.4.0

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.
@@ -216,7 +216,18 @@ async function main() {
216
216
  }
217
217
 
218
218
  // Create .developer-role file (default: fullstack = no restrictions)
219
- await fs.writeFile(path.join(targetDir, '.developer-role'), 'fullstack\n', 'utf-8');
219
+ const developerRoleContent = [
220
+ 'fullstack',
221
+ '# Available roles (change the first line to switch):',
222
+ '#',
223
+ '# frontend - Can edit client/ only. Cannot edit server/ files. Can read everything.',
224
+ '# backend - Can edit server/ only. Cannot edit client/ files. Can read everything.',
225
+ '# fullstack - Can edit everything. No restrictions.',
226
+ '#',
227
+ '# You can also switch roles using the /role command in Claude.',
228
+ '',
229
+ ].join('\n');
230
+ await fs.writeFile(path.join(targetDir, '.developer-role'), developerRoleContent, 'utf-8');
220
231
 
221
232
  spinner.succeed('Project scaffolded successfully!');
222
233
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-tigra",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "type": "module",
5
5
  "description": "Create a production-ready full-stack app with Next.js 16 + Fastify 5 + Prisma + Redis",
6
6
  "bin": {
@@ -14,9 +14,9 @@
14
14
 
15
15
  ROLE_FILE="$CLAUDE_PROJECT_DIR/.developer-role"
16
16
 
17
- # Read role from file, trim whitespace
17
+ # Read role from first non-comment, non-empty line
18
18
  if [ -f "$ROLE_FILE" ]; then
19
- ROLE=$(tr -d '[:space:]' < "$ROLE_FILE")
19
+ ROLE=$(grep -v '^\s*#' "$ROLE_FILE" | grep -v '^\s*$' | head -1 | tr -d '[:space:]')
20
20
  else
21
21
  ROLE=""
22
22
  fi
@@ -215,7 +215,15 @@ const apiClient = axios.create({ ...httpClient.defaults, baseURL: 'https://api.e
215
215
 
216
216
  ## File Storage
217
217
 
218
- Upload directory structure: `uploads/users/{userId}/<media-type>/`
218
+ ### Directory Structure Principles
219
+
220
+ Upload folders must be **scalable and manageable**. Never dump all files into a single flat directory (e.g., all product images under `/uploads/products/`). Instead, organize by **owner/entity ID** so each entity's files are isolated and easy to find, move, or delete.
221
+
222
+ **Pattern**: `uploads/<domain>/{entityId}/<media-type>/`
223
+
224
+ ### User Uploads
225
+
226
+ Structure: `uploads/users/{userId}/<media-type>/`
219
227
 
220
228
  | Media type | Path | Example |
221
229
  |---|---|---|
@@ -225,3 +233,22 @@ Upload directory structure: `uploads/users/{userId}/<media-type>/`
225
233
  - On account purge, delete the entire `uploads/users/{userId}/` directory via `deleteUserMedia()`.
226
234
  - Public URL pattern: `/uploads/users/{userId}/<media-type>/{filename}`
227
235
  - New media types follow the same pattern: add a subfolder under the user directory.
236
+
237
+ ### Domain Entity Uploads (Products, Articles, etc.)
238
+
239
+ Structure: `uploads/<domain>/{entityId}/<media-type>/`
240
+
241
+ | Domain | Media type | Path | Example |
242
+ |---|---|---|---|
243
+ | Products | Images | `uploads/products/{productId}/images/` | `uploads/products/prod-456/images/front-view.webp` |
244
+ | Products | Thumbnails | `uploads/products/{productId}/thumbnails/` | `uploads/products/prod-456/thumbnails/front-view-thumb.webp` |
245
+ | Articles | Cover | `uploads/articles/{articleId}/cover/` | `uploads/articles/art-789/cover/hero.webp` |
246
+ | Articles | Content images | `uploads/articles/{articleId}/content/` | `uploads/articles/art-789/content/diagram-1.webp` |
247
+
248
+ ### Rules
249
+
250
+ 1. **Never use flat directories** — `uploads/products/img1.jpg, img2.jpg, ...` is forbidden. Always namespace by entity ID.
251
+ 2. **One folder per entity instance** — makes deletion, migration, and backup trivial (`rm -rf uploads/products/{id}/`).
252
+ 3. **Separate media types into subfolders** — don't mix avatars, thumbnails, and full-size images in the same folder.
253
+ 4. **Entity cleanup** — when an entity is deleted, remove its entire upload directory (e.g., `uploads/products/{productId}/`).
254
+ 5. **Consistent naming** — use kebab-case for filenames, domain plural for top-level folders (`products`, `articles`, `users`).
@@ -34,7 +34,6 @@
34
34
  },
35
35
  "devDependencies": {
36
36
  "@tailwindcss/postcss": "^4",
37
- "@tanstack/react-query-devtools": "^5.91.3",
38
37
  "@types/node": "^20",
39
38
  "@types/react": "^19",
40
39
  "@types/react-dom": "^19",
Binary file
@@ -55,83 +55,85 @@
55
55
 
56
56
  :root {
57
57
  --radius: 0.625rem;
58
- --background: oklch(1 0 0);
59
- --foreground: oklch(0.145 0 0);
58
+ /* Claude palette: #f4f3ee (cream), #ffffff (white), #b1ada1 (warm gray), #c15f3c (orange) */
59
+ --background: oklch(0.964 0.007 97.5);
60
+ --foreground: oklch(0.205 0.015 92);
60
61
  --card: oklch(1 0 0);
61
- --card-foreground: oklch(0.145 0 0);
62
+ --card-foreground: oklch(0.205 0.015 92);
62
63
  --popover: oklch(1 0 0);
63
- --popover-foreground: oklch(0.145 0 0);
64
- --primary: oklch(0.45 0.2 260);
65
- --primary-foreground: oklch(0.985 0 0);
66
- --secondary: oklch(0.97 0 0);
67
- --secondary-foreground: oklch(0.205 0 0);
68
- --muted: oklch(0.97 0 0);
69
- --muted-foreground: oklch(0.556 0 0);
70
- --accent: oklch(0.97 0 0);
71
- --accent-foreground: oklch(0.205 0 0);
64
+ --popover-foreground: oklch(0.205 0.015 92);
65
+ --primary: oklch(0.597 0.135 39.9);
66
+ --primary-foreground: oklch(1 0 0);
67
+ --secondary: oklch(0.935 0.009 97.5);
68
+ --secondary-foreground: oklch(0.3 0.015 92);
69
+ --muted: oklch(0.935 0.009 97.5);
70
+ --muted-foreground: oklch(0.748 0.017 91.6);
71
+ --accent: oklch(0.935 0.009 97.5);
72
+ --accent-foreground: oklch(0.3 0.015 92);
72
73
  --destructive: oklch(0.577 0.245 27.325);
73
- --border: oklch(0.922 0 0);
74
- --input: oklch(0.922 0 0);
75
- --ring: oklch(0.45 0.2 260);
74
+ --border: oklch(0.895 0.012 97.5);
75
+ --input: oklch(0.895 0.012 97.5);
76
+ --ring: oklch(0.597 0.135 39.9);
76
77
  --success: oklch(0.52 0.17 155);
77
78
  --success-foreground: oklch(1 0 0);
78
- --warning: oklch(0.75 0.18 75);
79
- --warning-foreground: oklch(0.2 0 0);
79
+ --warning: oklch(0.75 0.15 70);
80
+ --warning-foreground: oklch(0.25 0.015 92);
80
81
  --info: oklch(0.55 0.15 240);
81
82
  --info-foreground: oklch(1 0 0);
82
- --chart-1: oklch(0.646 0.222 41.116);
83
+ --chart-1: oklch(0.597 0.135 39.9);
83
84
  --chart-2: oklch(0.6 0.118 184.704);
84
85
  --chart-3: oklch(0.398 0.07 227.392);
85
- --chart-4: oklch(0.828 0.189 84.429);
86
- --chart-5: oklch(0.769 0.188 70.08);
87
- --sidebar: oklch(0.985 0 0);
88
- --sidebar-foreground: oklch(0.145 0 0);
89
- --sidebar-primary: oklch(0.205 0 0);
90
- --sidebar-primary-foreground: oklch(0.985 0 0);
91
- --sidebar-accent: oklch(0.97 0 0);
92
- --sidebar-accent-foreground: oklch(0.205 0 0);
93
- --sidebar-border: oklch(0.922 0 0);
94
- --sidebar-ring: oklch(0.708 0 0);
86
+ --chart-4: oklch(0.828 0.12 84);
87
+ --chart-5: oklch(0.748 0.017 91.6);
88
+ --sidebar: oklch(0.95 0.007 97.5);
89
+ --sidebar-foreground: oklch(0.205 0.015 92);
90
+ --sidebar-primary: oklch(0.3 0.015 92);
91
+ --sidebar-primary-foreground: oklch(0.964 0.007 97.5);
92
+ --sidebar-accent: oklch(0.935 0.009 97.5);
93
+ --sidebar-accent-foreground: oklch(0.3 0.015 92);
94
+ --sidebar-border: oklch(0.895 0.012 97.5);
95
+ --sidebar-ring: oklch(0.597 0.135 39.9);
95
96
  }
96
97
 
97
98
  .dark {
98
- --background: oklch(0.145 0 0);
99
- --foreground: oklch(0.985 0 0);
100
- --card: oklch(0.205 0 0);
101
- --card-foreground: oklch(0.985 0 0);
102
- --popover: oklch(0.205 0 0);
103
- --popover-foreground: oklch(0.985 0 0);
104
- --primary: oklch(0.6 0.2 260);
105
- --primary-foreground: oklch(0.145 0 0);
106
- --secondary: oklch(0.269 0 0);
107
- --secondary-foreground: oklch(0.985 0 0);
108
- --muted: oklch(0.269 0 0);
109
- --muted-foreground: oklch(0.708 0 0);
110
- --accent: oklch(0.269 0 0);
111
- --accent-foreground: oklch(0.985 0 0);
99
+ /* Dark mode: inverted Claude palette with same warm undertone */
100
+ --background: oklch(0.185 0.012 92);
101
+ --foreground: oklch(0.93 0.007 97.5);
102
+ --card: oklch(0.235 0.012 92);
103
+ --card-foreground: oklch(0.93 0.007 97.5);
104
+ --popover: oklch(0.235 0.012 92);
105
+ --popover-foreground: oklch(0.93 0.007 97.5);
106
+ --primary: oklch(0.66 0.135 39.9);
107
+ --primary-foreground: oklch(0.185 0.012 92);
108
+ --secondary: oklch(0.28 0.012 92);
109
+ --secondary-foreground: oklch(0.93 0.007 97.5);
110
+ --muted: oklch(0.28 0.012 92);
111
+ --muted-foreground: oklch(0.65 0.015 91.6);
112
+ --accent: oklch(0.28 0.012 92);
113
+ --accent-foreground: oklch(0.93 0.007 97.5);
112
114
  --destructive: oklch(0.704 0.191 22.216);
113
- --border: oklch(1 0 0 / 10%);
114
- --input: oklch(1 0 0 / 15%);
115
- --ring: oklch(0.6 0.2 260);
115
+ --border: oklch(1 0.007 97.5 / 12%);
116
+ --input: oklch(1 0.007 97.5 / 15%);
117
+ --ring: oklch(0.66 0.135 39.9);
116
118
  --success: oklch(0.6 0.17 155);
117
119
  --success-foreground: oklch(1 0 0);
118
- --warning: oklch(0.8 0.18 75);
119
- --warning-foreground: oklch(0.2 0 0);
120
+ --warning: oklch(0.8 0.15 70);
121
+ --warning-foreground: oklch(0.25 0.015 92);
120
122
  --info: oklch(0.65 0.15 240);
121
123
  --info-foreground: oklch(1 0 0);
122
- --chart-1: oklch(0.488 0.243 264.376);
124
+ --chart-1: oklch(0.66 0.135 39.9);
123
125
  --chart-2: oklch(0.696 0.17 162.48);
124
- --chart-3: oklch(0.769 0.188 70.08);
125
- --chart-4: oklch(0.627 0.265 303.9);
126
- --chart-5: oklch(0.645 0.246 16.439);
127
- --sidebar: oklch(0.205 0 0);
128
- --sidebar-foreground: oklch(0.985 0 0);
129
- --sidebar-primary: oklch(0.488 0.243 264.376);
130
- --sidebar-primary-foreground: oklch(0.985 0 0);
131
- --sidebar-accent: oklch(0.269 0 0);
132
- --sidebar-accent-foreground: oklch(0.985 0 0);
133
- --sidebar-border: oklch(1 0 0 / 10%);
134
- --sidebar-ring: oklch(0.556 0 0);
126
+ --chart-3: oklch(0.769 0.12 70);
127
+ --chart-4: oklch(0.627 0.18 303.9);
128
+ --chart-5: oklch(0.645 0.17 16.439);
129
+ --sidebar: oklch(0.235 0.012 92);
130
+ --sidebar-foreground: oklch(0.93 0.007 97.5);
131
+ --sidebar-primary: oklch(0.66 0.135 39.9);
132
+ --sidebar-primary-foreground: oklch(0.93 0.007 97.5);
133
+ --sidebar-accent: oklch(0.28 0.012 92);
134
+ --sidebar-accent-foreground: oklch(0.93 0.007 97.5);
135
+ --sidebar-border: oklch(1 0.007 97.5 / 12%);
136
+ --sidebar-ring: oklch(0.66 0.135 39.9);
135
137
  }
136
138
 
137
139
  @layer base {
Binary file
@@ -1,45 +1,76 @@
1
- 'use client';
2
-
3
1
  import type React from 'react';
4
- import { LogOut } from 'lucide-react';
2
+ import type { Metadata } from 'next';
3
+
4
+ import Image from 'next/image';
5
5
 
6
- import { Button } from '@/components/ui/button';
7
- import { Skeleton } from '@/components/ui/skeleton';
8
- import { useAppSelector } from '@/store/hooks';
9
- import { useAuth } from '@/features/auth/hooks/useAuth';
10
6
  import { APP_NAME } from '@/lib/constants/app.constants';
11
7
 
12
- export default function WelcomePage(): React.ReactElement {
13
- const { user } = useAppSelector((state) => state.auth);
14
- const { logout, isLoggingOut } = useAuth();
8
+ export const metadata: Metadata = {
9
+ title: APP_NAME,
10
+ description: `Welcome to ${APP_NAME} generated with create-tigra`,
11
+ };
15
12
 
13
+ export default function WelcomePage(): React.ReactElement {
16
14
  return (
17
- <div className="flex min-h-dvh flex-col">
18
- <header className="flex items-center justify-between px-6 py-4">
19
- <span className="text-lg font-semibold tracking-tight text-foreground">
15
+ <div className="relative flex min-h-dvh flex-col items-center justify-center overflow-hidden px-6">
16
+ {/* Ambient glow */}
17
+ <div
18
+ aria-hidden="true"
19
+ className="pointer-events-none absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"
20
+ >
21
+ <div className="motion-safe:animate-pulse h-64 w-64 rounded-full bg-primary/15 blur-3xl md:h-96 md:w-96" />
22
+ </div>
23
+
24
+ {/* Content */}
25
+ <div className="relative z-10 flex max-w-md flex-col items-center text-center">
26
+ {/* Logo */}
27
+ <div className="mb-8">
28
+ <Image
29
+ src="/logo.png"
30
+ alt={`${APP_NAME} logo`}
31
+ width={160}
32
+ height={160}
33
+ priority
34
+ className="h-32 w-32 md:h-40 md:w-40"
35
+ />
36
+ </div>
37
+
38
+ <h1 className="text-3xl font-bold tracking-tight text-foreground md:text-4xl">
20
39
  {APP_NAME}
21
- </span>
22
- <Button
23
- variant="ghost"
24
- size="sm"
25
- onClick={logout}
26
- disabled={isLoggingOut}
27
- className="text-muted-foreground transition-colors duration-150 hover:text-foreground"
28
- >
29
- <LogOut className="mr-2 h-4 w-4" />
30
- Sign out
31
- </Button>
32
- </header>
33
-
34
- <main className="flex flex-1 items-center justify-center">
35
- {user ? (
36
- <h1 className="text-3xl font-light tracking-tight text-foreground">
37
- Welcome, {user.firstName}
38
- </h1>
39
- ) : (
40
- <Skeleton className="h-9 w-64" />
41
- )}
42
- </main>
40
+ </h1>
41
+
42
+ <p className="mt-3 text-base text-muted-foreground md:text-lg">
43
+ Generated with{' '}
44
+ <span className="font-semibold text-foreground">create-tigra</span>
45
+ </p>
46
+
47
+ <div className="mt-8 flex flex-col gap-3 sm:flex-row sm:gap-4">
48
+ <a
49
+ href="https://github.com/BehzodKarimov/create-tigra"
50
+ target="_blank"
51
+ rel="noopener noreferrer"
52
+ className="inline-flex min-h-11 items-center justify-center rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all duration-200 active:scale-[0.97] md:hover:brightness-110"
53
+ >
54
+ Documentation
55
+ </a>
56
+ <a
57
+ href="https://github.com/BehzodKarimov/create-tigra/issues"
58
+ target="_blank"
59
+ rel="noopener noreferrer"
60
+ className="inline-flex min-h-11 items-center justify-center rounded-lg border border-border bg-secondary px-5 py-2.5 text-sm font-medium text-secondary-foreground transition-all duration-200 active:scale-[0.97] md:hover:bg-accent"
61
+ >
62
+ Report an issue
63
+ </a>
64
+ </div>
65
+
66
+ <p className="mt-12 font-mono text-xs text-muted-foreground md:text-sm">
67
+ Edit{' '}
68
+ <code className="rounded-md bg-muted px-1.5 py-0.5">
69
+ src/app/page.tsx
70
+ </code>{' '}
71
+ to get started
72
+ </p>
73
+ </div>
43
74
  </div>
44
75
  );
45
76
  }
@@ -4,7 +4,6 @@ import type React from 'react';
4
4
  import { useState } from 'react';
5
5
 
6
6
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
7
- import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
8
7
  import { Provider as ReduxProvider } from 'react-redux';
9
8
  import { ThemeProvider } from 'next-themes';
10
9
  import { Toaster } from 'sonner';
@@ -36,7 +35,6 @@ export function Providers({ children }: { children: React.ReactNode }): React.Re
36
35
  </AuthInitializer>
37
36
  <Toaster position="top-right" richColors />
38
37
  </ThemeProvider>
39
- {process.env.NODE_ENV === 'development' && <ReactQueryDevtools initialIsOpen={false} />}
40
38
  </QueryClientProvider>
41
39
  </ReduxProvider>
42
40
  );
@@ -0,0 +1,48 @@
1
+ 'use client';
2
+
3
+ import type React from 'react';
4
+
5
+ import Image from 'next/image';
6
+ import type { ImageProps } from 'next/image';
7
+
8
+ /**
9
+ * Wraps Next.js <Image> to bypass the optimization proxy for localhost URLs.
10
+ *
11
+ * Next.js refuses to fetch images from loopback IPs (127.0.0.1, ::1) through
12
+ * its optimization proxy — even when remotePatterns allows localhost. This is
13
+ * a security restriction to prevent SSRF attacks.
14
+ *
15
+ * SafeImage detects localhost/loopback URLs and sets `unoptimized` so the
16
+ * image loads directly via a regular <img> tag. In production with a real
17
+ * domain, images are optimized normally.
18
+ */
19
+
20
+ const LOOPBACK_PATTERNS = [
21
+ 'localhost',
22
+ '127.0.0.1',
23
+ '0.0.0.0',
24
+ '[::1]',
25
+ ] as const;
26
+
27
+ function isLoopbackUrl(src: ImageProps['src']): boolean {
28
+ if (typeof src !== 'string') return false;
29
+
30
+ try {
31
+ const url = new URL(src);
32
+ return LOOPBACK_PATTERNS.some((pattern) => url.hostname === pattern);
33
+ } catch {
34
+ // Relative path or invalid URL — not a loopback issue
35
+ return false;
36
+ }
37
+ }
38
+
39
+ export const SafeImage = (props: ImageProps): React.ReactElement => {
40
+ const shouldSkipOptimization = isLoopbackUrl(props.src);
41
+
42
+ return (
43
+ <Image
44
+ {...props}
45
+ unoptimized={props.unoptimized || shouldSkipOptimization}
46
+ />
47
+ );
48
+ };
@@ -38,7 +38,7 @@ export const useAuth = (): UseAuthReturn => {
38
38
  dispatch(setUser(data.user));
39
39
  toast.success('Signed in successfully');
40
40
  const from = searchParams.get('from');
41
- const redirectTo = from && from.startsWith('/') && !from.startsWith('//') ? from : '/';
41
+ const redirectTo = from && from.startsWith('/') && !from.startsWith('//') ? from : ROUTES.DASHBOARD;
42
42
  router.push(redirectTo);
43
43
  },
44
44
  onError: (error) => {
@@ -51,7 +51,7 @@ export const useAuth = (): UseAuthReturn => {
51
51
  onSuccess: (data) => {
52
52
  dispatch(setUser(data.user));
53
53
  toast.success('Account created successfully');
54
- router.push(ROUTES.HOME);
54
+ router.push(ROUTES.DASHBOARD);
55
55
  },
56
56
  onError: (error) => {
57
57
  toast.error(getErrorMessage(error));
@@ -9,9 +9,6 @@ const apiClient = axios.create({
9
9
  baseURL: process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000/api/v1',
10
10
  timeout: 30000,
11
11
  withCredentials: true, // Send cookies with every request
12
- headers: {
13
- 'Content-Type': 'application/json',
14
- },
15
12
  });
16
13
 
17
14
  // No request interceptor needed — cookies are sent automatically
@@ -46,8 +43,15 @@ apiClient.interceptors.response.use(
46
43
  return Promise.reject(error);
47
44
  }
48
45
 
49
- // Don't retry refresh endpoint itself
50
- if (originalRequest.url === API_ENDPOINTS.AUTH.REFRESH) {
46
+ // Don't retry auth endpoints that don't use tokens —
47
+ // a 401 here means wrong credentials, not an expired token.
48
+ const noRetryEndpoints = [
49
+ API_ENDPOINTS.AUTH.LOGIN,
50
+ API_ENDPOINTS.AUTH.REGISTER,
51
+ API_ENDPOINTS.AUTH.REFRESH,
52
+ API_ENDPOINTS.AUTH.RESET_PASSWORD,
53
+ ];
54
+ if (noRetryEndpoints.includes(originalRequest.url ?? '')) {
51
55
  return Promise.reject(error);
52
56
  }
53
57
 
@@ -57,6 +61,8 @@ apiClient.interceptors.response.use(
57
61
  resetRefreshState();
58
62
  }
59
63
 
64
+ originalRequest._retry = true;
65
+
60
66
  if (isRefreshing) {
61
67
  return new Promise<void>((resolve, reject) => {
62
68
  failedQueue.push({ resolve, reject });
@@ -64,8 +70,6 @@ apiClient.interceptors.response.use(
64
70
  return apiClient(originalRequest);
65
71
  });
66
72
  }
67
-
68
- originalRequest._retry = true;
69
73
  isRefreshing = true;
70
74
  refreshTimestamp = Date.now();
71
75
 
@@ -94,6 +98,9 @@ apiClient.interceptors.response.use(
94
98
  store.dispatch(logout());
95
99
 
96
100
  if (typeof window !== 'undefined') {
101
+ // Clear session indicator so middleware won't let user through
102
+ // to protected pages — prevents redirect loops
103
+ document.cookie = 'auth_session=; Max-Age=0; path=/; SameSite=Strict';
97
104
  window.location.href = ROUTES.LOGIN;
98
105
  }
99
106
  }
@@ -2,8 +2,7 @@ import { NextResponse } from 'next/server';
2
2
 
3
3
  import type { NextRequest } from 'next/server';
4
4
 
5
- const protectedPaths = ['/', '/dashboard', '/profile', '/admin'];
6
- const authPaths = ['/login', '/register'];
5
+ const protectedPaths = ['/dashboard', '/profile', '/admin'];
7
6
 
8
7
  function isTokenExpired(token: string): boolean {
9
8
  try {
@@ -17,38 +16,33 @@ function isTokenExpired(token: string): boolean {
17
16
 
18
17
  export function middleware(request: NextRequest): NextResponse {
19
18
  const { pathname } = request.nextUrl;
20
- const token = request.cookies.get('access_token')?.value;
19
+ const accessToken = request.cookies.get('access_token')?.value;
20
+ const authSession = request.cookies.get('auth_session')?.value;
21
21
 
22
- const isProtectedPath = protectedPaths.some((path) =>
23
- path === '/' ? pathname === '/' : pathname.startsWith(path)
24
- );
22
+ const isProtectedPath = protectedPaths.some((path) => pathname.startsWith(path));
25
23
 
26
- // No token at all — user is not logged in, redirect to login
27
- if (isProtectedPath && !token) {
28
- const loginUrl = new URL('/login', request.url);
29
- loginUrl.searchParams.set('from', pathname);
30
- return NextResponse.redirect(loginUrl);
31
- }
32
-
33
- // Expired token on protected path — allow through so client-side can attempt refresh.
34
- // Delete the stale access_token so AuthInitializer starts fresh: getMe() → 401 → refresh.
35
- if (isProtectedPath && token && isTokenExpired(token)) {
36
- const response = NextResponse.next();
37
- response.cookies.delete('access_token');
38
- return response;
39
- }
24
+ if (isProtectedPath) {
25
+ // No access_token AND no auth_session — truly unauthenticated
26
+ if (!accessToken && !authSession) {
27
+ const loginUrl = new URL('/login', request.url);
28
+ loginUrl.searchParams.set('from', pathname);
29
+ return NextResponse.redirect(loginUrl);
30
+ }
40
31
 
41
- const isAuthPath = authPaths.some((path) => pathname.startsWith(path));
32
+ // No access_token BUT auth_session exists — session is alive,
33
+ // let through so client-side can do getMe() → 401 → refresh → retry
34
+ if (!accessToken && authSession) {
35
+ return NextResponse.next();
36
+ }
42
37
 
43
- if (isAuthPath && token) {
44
- if (isTokenExpired(token)) {
45
- // Only delete the expired access token — keep the refresh token
46
- // so the client-side interceptor can still recover the session
38
+ // Expired access_token delete stale cookie, let through for client-side refresh
39
+ if (accessToken && isTokenExpired(accessToken)) {
47
40
  const response = NextResponse.next();
48
41
  response.cookies.delete('access_token');
49
42
  return response;
50
43
  }
51
- return NextResponse.redirect(new URL('/', request.url));
44
+
45
+ return NextResponse.next();
52
46
  }
53
47
 
54
48
  return NextResponse.next();
@@ -56,11 +50,8 @@ export function middleware(request: NextRequest): NextResponse {
56
50
 
57
51
  export const config = {
58
52
  matcher: [
59
- '/',
60
53
  '/dashboard/:path*',
61
54
  '/profile/:path*',
62
55
  '/admin/:path*',
63
- '/login',
64
- '/register',
65
56
  ],
66
57
  };
@@ -94,6 +94,15 @@ JWT_REFRESH_EXPIRY="7d"
94
94
  # For production: generate a separate secret: openssl rand -base64 48
95
95
  # COOKIE_SECRET="change-this-to-a-different-secret-at-least-32-chars"
96
96
 
97
+ # Cookie domain for cross-origin deployments
98
+ # REQUIRED when client and API are on different subdomains:
99
+ # Client: https://app.example.com | API: https://api.example.com
100
+ # → Set COOKIE_DOMAIN=".example.com" (note the leading dot)
101
+ # NOT needed when client and API share the same hostname (local dev, same-origin prod)
102
+ # Without this, cookies are scoped to the API hostname only and the browser
103
+ # will silently reject them on cross-origin requests (login appears to do nothing).
104
+ # COOKIE_DOMAIN=".example.com"
105
+
97
106
  # ===================================================================
98
107
  # CORS (Cross-Origin Resource Sharing)
99
108
  # ===================================================================
@@ -80,6 +80,14 @@ JWT_REFRESH_EXPIRY="7d"
80
80
  # Multiple origins separated by commas
81
81
  CORS_ORIGIN="https://yourdomain.com,https://app.yourdomain.com"
82
82
 
83
+ # Cookie domain for cross-origin deployments
84
+ # REQUIRED when client and API are on different subdomains:
85
+ # Client: https://app.example.com | API: https://api.example.com
86
+ # → Set COOKIE_DOMAIN=".example.com" (leading dot = all subdomains)
87
+ # This enables cookies to be shared between client and API subdomains.
88
+ # Without it, login will silently fail (server returns 200 but browser drops cookies).
89
+ COOKIE_DOMAIN=".yourdomain.com"
90
+
83
91
  # ===================================================================
84
92
  # LOGGING
85
93
  # ===================================================================
@@ -102,6 +110,7 @@ SENTRY_DSN="https://YOUR_PUBLIC_KEY@o0.ingest.sentry.io/YOUR_PROJECT_ID"
102
110
  # [ ] DATABASE_URL uses secure credentials and SSL
103
111
  # [ ] JWT_SECRET is a strong random string (48+ chars)
104
112
  # [ ] CORS_ORIGIN is set to your exact frontend URL(s)
113
+ # [ ] COOKIE_DOMAIN is set if client and API are on different subdomains
105
114
  # [ ] REDIS_URL uses authentication if Redis is exposed
106
115
  # [ ] LOG_LEVEL is set to info or warn
107
116
  # [ ] SENTRY_DSN is configured for error tracking
@@ -39,6 +39,12 @@ const envSchema = z.object({
39
39
  // Separate secret for cookie signing (defaults to JWT_SECRET if not set)
40
40
  COOKIE_SECRET: z.string().min(32, 'COOKIE_SECRET must be at least 32 characters').optional(),
41
41
 
42
+ // Cookie domain for cross-origin deployments (client ≠ server hostname)
43
+ // Required when client and API are on different subdomains (e.g., app.example.com + api.example.com)
44
+ // Set to the shared parent domain with a leading dot: ".example.com"
45
+ // Leave empty for same-origin deployments or local development
46
+ COOKIE_DOMAIN: z.string().optional(),
47
+
42
48
  // --- CORS ---
43
49
  // In development: CORS_ORIGIN is optional (allows all origins)
44
50
  // In production: REQUIRED for security
@@ -4,6 +4,14 @@ import { parseDurationMs } from '@libs/auth.js';
4
4
 
5
5
  const isProduction = env.NODE_ENV === 'production';
6
6
 
7
+ // Cross-origin deployment: client and API on different subdomains require sameSite 'none'.
8
+ // Same-origin deployment (or local dev): 'strict' is the safest default.
9
+ const isCrossOrigin = Boolean(env.COOKIE_DOMAIN);
10
+ const sameSitePolicy = isProduction && isCrossOrigin ? 'none' as const : 'strict' as const;
11
+
12
+ // When set, cookies are shared across subdomains (e.g., ".example.com" covers app.example.com + api.example.com)
13
+ const cookieDomain = env.COOKIE_DOMAIN || undefined;
14
+
7
15
  const ACCESS_TOKEN_MAX_AGE_MS = parseDurationMs(env.JWT_ACCESS_EXPIRY, 15 * 60 * 1000);
8
16
  const REFRESH_TOKEN_MAX_AGE_MS = parseDurationMs(env.JWT_REFRESH_EXPIRY, 7 * 24 * 60 * 60 * 1000);
9
17
 
@@ -15,7 +23,8 @@ export function setAuthCookies(
15
23
  reply.setCookie('access_token', accessToken, {
16
24
  httpOnly: true,
17
25
  secure: isProduction,
18
- sameSite: 'strict',
26
+ sameSite: sameSitePolicy,
27
+ domain: cookieDomain,
19
28
  path: '/',
20
29
  maxAge: Math.floor(ACCESS_TOKEN_MAX_AGE_MS / 1000), // setCookie expects seconds
21
30
  });
@@ -23,24 +32,46 @@ export function setAuthCookies(
23
32
  reply.setCookie('refresh_token', refreshToken, {
24
33
  httpOnly: true,
25
34
  secure: isProduction,
26
- sameSite: 'strict',
35
+ sameSite: sameSitePolicy,
36
+ domain: cookieDomain,
27
37
  path: '/api/v1/auth',
28
38
  maxAge: Math.floor(REFRESH_TOKEN_MAX_AGE_MS / 1000),
29
39
  });
40
+
41
+ // Non-sensitive session indicator visible to Next.js middleware and client JS.
42
+ // Lets middleware distinguish "never logged in" from "access token expired but session alive."
43
+ reply.setCookie('auth_session', '1', {
44
+ httpOnly: false,
45
+ secure: isProduction,
46
+ sameSite: sameSitePolicy,
47
+ domain: cookieDomain,
48
+ path: '/',
49
+ maxAge: Math.floor(REFRESH_TOKEN_MAX_AGE_MS / 1000),
50
+ });
30
51
  }
31
52
 
32
53
  export function clearAuthCookies(reply: FastifyReply): void {
33
54
  reply.clearCookie('access_token', {
34
55
  httpOnly: true,
35
56
  secure: isProduction,
36
- sameSite: 'strict',
57
+ sameSite: sameSitePolicy,
58
+ domain: cookieDomain,
37
59
  path: '/',
38
60
  });
39
61
 
40
62
  reply.clearCookie('refresh_token', {
41
63
  httpOnly: true,
42
64
  secure: isProduction,
43
- sameSite: 'strict',
65
+ sameSite: sameSitePolicy,
66
+ domain: cookieDomain,
44
67
  path: '/api/v1/auth',
45
68
  });
69
+
70
+ reply.clearCookie('auth_session', {
71
+ httpOnly: false,
72
+ secure: isProduction,
73
+ sameSite: sameSitePolicy,
74
+ domain: cookieDomain,
75
+ path: '/',
76
+ });
46
77
  }
@@ -1,18 +0,0 @@
1
- import type React from 'react';
2
-
3
- import { APP_NAME } from '@/lib/constants/app.constants';
4
-
5
- export default function AuthLayout({
6
- children,
7
- }: {
8
- children: React.ReactNode;
9
- }): React.ReactElement {
10
- return (
11
- <div className="flex min-h-dvh flex-col items-center justify-center px-4 py-12">
12
- <span className="mb-8 text-xl font-semibold tracking-tight text-foreground">
13
- {APP_NAME}
14
- </span>
15
- {children}
16
- </div>
17
- );
18
- }
@@ -1,13 +0,0 @@
1
- import type React from 'react';
2
-
3
- import { LoginForm } from '@/features/auth/components/LoginForm';
4
-
5
- import type { Metadata } from 'next';
6
-
7
- export const metadata: Metadata = {
8
- title: 'Sign in',
9
- };
10
-
11
- export default function LoginPage(): React.ReactElement {
12
- return <LoginForm />;
13
- }
@@ -1,13 +0,0 @@
1
- import type React from 'react';
2
-
3
- import { RegisterForm } from '@/features/auth/components/RegisterForm';
4
-
5
- import type { Metadata } from 'next';
6
-
7
- export const metadata: Metadata = {
8
- title: 'Create account',
9
- };
10
-
11
- export default function RegisterPage(): React.ReactElement {
12
- return <RegisterForm />;
13
- }
@@ -1,22 +0,0 @@
1
- import type React from 'react';
2
-
3
- import type { Metadata } from 'next';
4
-
5
- export const metadata: Metadata = {
6
- title: 'Dashboard',
7
- };
8
-
9
- export default function DashboardPage(): React.ReactElement {
10
- return (
11
- <div className="container mx-auto px-4 py-12 md:px-6 lg:px-8">
12
- <div className="space-y-6">
13
- <div>
14
- <h1 className="text-3xl font-bold tracking-tight">Dashboard</h1>
15
- <p className="mt-2 text-muted-foreground">
16
- Welcome to your dashboard. This is where you&apos;ll manage everything.
17
- </p>
18
- </div>
19
- </div>
20
- </div>
21
- );
22
- }
@@ -1,11 +0,0 @@
1
- import type React from 'react';
2
-
3
- import { MainLayout } from '@/components/layout/MainLayout';
4
-
5
- export default function MainGroupLayout({
6
- children,
7
- }: {
8
- children: React.ReactNode;
9
- }): React.ReactElement {
10
- return <MainLayout>{children}</MainLayout>;
11
- }
Binary file