Generate a fully functional, multi-page Next.js MVP application for 'Resilience Shield', a SaaS platform designed to enhance cloud infrastructure resilience against disruptions. The application should be built using the App Router, Tailwind CSS, and Drizzle ORM with PostgreSQL. The primary goal is to provide real-time threat monitoring, intelligent alerting, and automated failover planning to minimize service downtime for businesses.
PROJECT OVERVIEW:
Resilience Shield addresses the critical business problem of infrastructure downtime caused by geopolitical events, cyberattacks, and natural disasters. Following incidents like the Iranian missile strikes on AWS data centers in Bahrain and Dubai, which caused significant service disruptions, businesses need a proactive solution. Our platform provides real-time monitoring of global events affecting major cloud providers (AWS, Azure, GCP), intelligent alerting based on customizable thresholds and critical event detection, and tools for planning and simulating automated failover mechanisms. The core value proposition is ensuring business continuity, minimizing financial losses, and protecting brand reputation by proactively managing infrastructure risks and enabling rapid response to disruptions.
TECH STACK:
- Frontend: React (Next.js 14+ with App Router)
- Styling: Tailwind CSS
- UI Components: shadcn/ui (built on Radix UI & Tailwind CSS)
- ORM: Drizzle ORM
- Database: PostgreSQL (with Neon.tech or similar managed service recommended for cloud deployment)
- Authentication: NextAuth.js (v5+ with PostgreSQL adapter for Drizzle)
- State Management: React Context API / Zustand (for global state where needed)
- API Layer: Server Actions and Route Handlers (Next.js)
- Libraries: `react-icons`, `chart.js` or `recharts` for dashboard visualizations, `date-fns` for date manipulation, `clsx` for conditional class names.
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
1. `users` table:
- `id`: uuid PRIMARY KEY (generated by pgcrypto or uuid-ossp)
- `name`: TEXT
- `email`: TEXT UNIQUE NOT NULL
- `emailVerified`: timestamp with time zone
- `image`: TEXT
- `createdAt`: timestamp with time zone DEFAULT now()
- `updatedAt`: timestamp with time zone DEFAULT now()
2. `accounts` table (for NextAuth.js):
- `id`: bigserial PRIMARY KEY
- `userId`: uuid REFERENCES `users`(`id`) ON DELETE CASCADE
- `type`: TEXT NOT NULL
- `provider`: TEXT NOT NULL
- `providerAccountId`: TEXT NOT NULL
- `refresh_token`: TEXT
- `access_token`: TEXT
- `expires_at`: bigint
- `token_type`: TEXT
- `scope`: TEXT
- `id_token`: TEXT
- `session_state`: TEXT
- `createdAt`: timestamp with time zone DEFAULT now()
- `updatedAt`: timestamp with time zone DEFAULT now()
- CONSTRAINT `accounts_provider_providerAccountId_unique` UNIQUE (`provider`, `providerAccountId`)
3. `sessions` table (for NextAuth.js):
- `sessionToken`: TEXT PRIMARY KEY
- `userId`: uuid REFERENCES `users`(`id`) ON DELETE CASCADE
- `expires`: timestamp with time zone NOT NULL
- `createdAt`: timestamp with time zone DEFAULT now()
- `updatedAt`: timestamp with time zone DEFAULT now()
4. `verificationTokens` table (for NextAuth.js):
- `identifier`: TEXT NOT NULL
- `token`: TEXT NOT NULL
- `expires`: timestamp with time zone NOT NULL
- CONSTRAINT `verificationTokens_identifier_token_unique` UNIQUE (`identifier`, `token`)
5. `monitoringRegions` table:
- `id`: uuid PRIMARY KEY DEFAULT gen_random_uuid()
- `userId`: uuid REFERENCES `users`(`id`) ON DELETE CASCADE
- `name`: TEXT NOT NULL -- e.g., 'AWS US-East-1', 'Azure West Europe'
- `provider`: VARCHAR(50) NOT NULL -- 'AWS', 'Azure', 'GCP'
- `region`: VARCHAR(100) NOT NULL -- e.g., 'us-east-1', 'westeurope'
- `isActive`: BOOLEAN DEFAULT true
- `createdAt`: timestamp with time zone DEFAULT now()
- `updatedAt`: timestamp with time zone DEFAULT now()
6. `alertThresholds` table:
- `id`: uuid PRIMARY KEY DEFAULT gen_random_uuid()
- `userId`: uuid REFERENCES `users`(`id`) ON DELETE CASCADE
- `monitoringRegionId`: uuid REFERENCES `monitoringRegions`(`id`) ON DELETE CASCADE
- `metric`: VARCHAR(100) NOT NULL -- e.g., 'latency', 'packet_loss', 'service_outage', 'geopolitical_risk_score'
- `operator`: VARCHAR(10) NOT NULL -- '>', '<', '=', '!=', 'contains'
- `value`: TEXT NOT NULL -- Threshold value (e.g., '100ms', '50%', 'critical')
- `alertLevel`: VARCHAR(20) NOT NULL -- 'INFO', 'WARNING', 'CRITICAL'
- `isActive`: BOOLEAN DEFAULT true
- `createdAt`: timestamp with time zone DEFAULT now()
- `updatedAt`: timestamp with time zone DEFAULT now()
7. `alerts` table:
- `id`: uuid PRIMARY KEY DEFAULT gen_random_uuid()
- `userId`: uuid REFERENCES `users`(`id`) ON DELETE CASCADE
- `monitoringRegionId`: uuid REFERENCES `monitoringRegions`(`id`) ON DELETE SET NULL
- `eventDescription`: TEXT NOT NULL
- `eventType`: VARCHAR(50) NOT NULL -- 'Cloud Provider Status', 'Cyber Attack', 'Geopolitical Event', 'Natural Disaster'
- `severity`: VARCHAR(20) NOT NULL -- 'INFO', 'WARNING', 'CRITICAL'
- `occurredAt`: timestamp with time zone NOT NULL
- `resolvedAt`: timestamp with time zone
- `status`: VARCHAR(20) NOT NULL DEFAULT 'ACTIVE' -- 'ACTIVE', 'RESOLVED', 'IGNORED'
- `createdAt`: timestamp with time zone DEFAULT now()
8. `failoverPlans` table:
- `id`: uuid PRIMARY KEY DEFAULT gen_random_uuid()
- `userId`: uuid REFERENCES `users`(`id`) ON DELETE CASCADE
- `name`: TEXT NOT NULL -- e.g., 'Primary Web App Failover'
- `description`: TEXT
- `primaryTarget`: TEXT NOT NULL -- e.g., 'AWS us-east-1'
- `failoverTarget`: TEXT NOT NULL -- e.g., 'Azure West Europe'
- `triggerConditions`: JSONB -- Conditions for failover (e.g., specific alerts, latency thresholds)
- `steps`: JSONB -- Sequence of actions for failover (e.g., DNS update, traffic redirection)
- `isActive`: BOOLEAN DEFAULT false
- `isSimulated`: BOOLEAN DEFAULT false
- `createdAt`: timestamp with time zone DEFAULT now()
- `updatedAt`: timestamp with time zone DEFAULT now()
CORE FEATURES & USER FLOW:
1. Authentication:
- User lands on the homepage.
- Clicks 'Sign Up' or 'Login'.
- Redirected to the NextAuth.js sign-in page.
- Options: Email/Password (using credentials provider), Google OAuth, GitHub OAuth.
- Upon successful login, user is redirected to the main dashboard.
- Protected routes (`/dashboard`, `/settings`, etc.) redirect to login if the user is not authenticated.
2. Region Monitoring Setup:
- Logged-in user navigates to 'Settings' -> 'Monitoring Regions'.
- Clicks 'Add Region'.
- Form appears: Provider (AWS, Azure, GCP), Region Name (e.g., 'us-east-1'), User-defined Name (e.g., 'My Primary AWS Region').
- On Submit: Server Action validates input, creates a new record in `monitoringRegions` linked to the user.
- User can enable/disable regions.
3. Alert Threshold Configuration:
- User navigates to 'Settings' -> 'Alert Thresholds'.
- Clicks 'Add Threshold'.
- Form appears: Select Monitoring Region, Metric (Latency, Outage, etc.), Operator, Value, Alert Level (INFO, WARNING, CRITICAL).
- On Submit: Server Action validates input, creates a new record in `alertThresholds` linked to the user and selected region.
- User can enable/disable thresholds.
4. Real-time Event Ingestion (Simulated for MVP):
- A background process (or simulated cron job/external webhook) checks external APIs (e.g., AWS Health Dashboard, Downdetector, news APIs for geopolitical events) or receives simulated data.
- If an event matches a user's monitored region or a critical global event occurs:
- A new record is created in the `alerts` table.
- Alert level and type are determined.
- If the alert matches a configured threshold for a user, an email notification is sent using a service like Resend or Nodemailer.
5. Dashboard View:
- On load, fetches user-specific data:
- Active alerts (`alerts` table, status='ACTIVE').
- Configured monitoring regions (`monitoringRegions` table).
- Upcoming/simulated failover plans (`failoverPlans` table).
- Displays a global threat map (using a library like react-leaflet or Mapbox GL JS) with markers for active alerts/regions.
- Shows key metrics/stats (e.g., 'Active Critical Alerts', 'Regions Monitored', 'Recent Disruptions').
- Includes a feed of recent alerts.
6. Failover Plan Creation & Simulation:
- User navigates to 'Failover Plans'.
- Clicks 'Create Plan'.
- Form: Plan Name, Description, Primary Target, Failover Target.
- Defines Trigger Conditions (e.g., 'When alert type is CYBER_ATTACK and severity is CRITICAL for Primary Target'). This could be a simple UI or JSON input for MVP.
- Defines Steps (e.g., '1. Update DNS record X', '2. Notify Operations Team via Webhook'). This is likely JSONB input.
- User can toggle `isActive` to enable the plan (for future automation) or `isSimulated` to run a simulation.
- Simulation: Backend logic checks if trigger conditions are met based on current/recent alerts. If met, it logs the intended actions without executing them and provides a simulation report.
API & DATA FETCHING:
- Use Next.js Server Actions for mutations (creating/updating regions, thresholds, plans).
- Use Route Handlers for read operations where necessary or when streaming data is beneficial.
- Fetch data for dashboard and settings pages within Server Components on the client side using `fetch` or libraries like SWR/React Query, leveraging Server Actions/Route Handlers.
- Example Server Action for creating a region:
```javascript
// app/actions.js
'use server';
import { db } from '@/lib/db'; // Your Drizzle connection
import { monitoringRegions } from '@/lib/db/schema';
import { auth } from '@/lib/auth'; // Your NextAuth.js setup
import { eq } from 'drizzle-orm';
import { revalidatePath } from 'next/cache';
export async function createMonitoringRegion(formData) {
const session = await auth();
if (!session?.user?.id) {
throw new Error('Unauthorized');
}
const { provider, region, name } = Object.fromEntries(formData.entries());
await db.insert(monitoringRegions).values({
userId: session.user.id,
provider: provider.toString(),
region: region.toString(),
name: name.toString(),
isActive: true,
});
revalidatePath('/settings/monitoring'); // Invalidate cache for the settings page
return { message: 'Region added successfully' };
}
```
- Data fetching in Server Components:
```jsx
// app/dashboard/page.jsx
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { alerts, monitoringRegions } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import AlertFeed from './_components/AlertFeed';
async function DashboardPage() {
const session = await auth();
if (!session?.user?.id) {
// Handle redirect or show login prompt
return <div>Please log in.</div>;
}
const activeAlerts = await db.query.alerts.findMany({
where: (a, { eq, and })
=> and(eq(a.userId, session.user.id), eq(a.status, 'ACTIVE')),
orderBy: (a, { desc })
=> desc(a.occurredAt),
limit: 10,
});
const monitoredRegions = await db.query.monitoringRegions.findMany({
where: eq(monitoringRegions.userId, session.user.id),
});
return (
<div>
<h1>Dashboard</h1>
<p>Welcome, {session.user.name}!</p>
<AlertFeed initialAlerts={activeAlerts} />
{/* ... other dashboard components ... */}
</div>
);
}
```
COMPONENT BREAKDOWN (Next.js App Router Structure):
- `app/layout.jsx`: Root layout (html, body, global providers like NextAuth, Tailwind classes).
- `app/page.jsx`: Landing Page (marketing content, sign-up/login CTA).
- `app/(auth)/signin/page.jsx`: Sign-in page using NextAuth.js components.
- `app/(protected)/layout.jsx`: Protected route layout (includes Navbar, Sidebar).
- `app/(protected)/dashboard/page.jsx`: Main dashboard view.
- `./_components/ThreatMap.jsx`: Interactive map showing global threats.
- `./_components/AlertFeed.jsx`: List of recent/active alerts.
- `./_components/StatsWidgets.jsx`: Key performance indicators.
- `app/(protected)/settings/page.jsx`: Settings overview.
- `app/(protected)/settings/monitoring/page.jsx`: Manage monitoring regions.
- `./_components/RegionList.jsx`: Table/list of configured regions.
- `./_components/RegionForm.jsx`: Modal/form to add/edit regions.
- `app/(protected)/settings/thresholds/page.jsx`: Manage alert thresholds.
- `./_components/ThresholdList.jsx`: Table/list of thresholds.
- `./_components/ThresholdForm.jsx`: Modal/form to add/edit thresholds.
- `app/(protected)/failover/page.jsx`: Manage failover plans.
- `./_components/PlanList.jsx`: Table/list of failover plans.
- `./_components/PlanForm.jsx`: Modal/form to create/edit plans.
- `./_components/SimulationButton.jsx`: Button to trigger plan simulation.
- `app/api/auth/[...nextauth]/route.js`: NextAuth.js API route.
- `lib/db.js`: Drizzle ORM database connection setup.
- `lib/db/schema.js`: Drizzle schema definitions.
- `lib/auth.js`: NextAuth.js configuration.
- `components/ui/`: Re-exported shadcn/ui components (Button, Input, Card, Table, Sheet, Dialog, etc.).
- `components/Navbar.jsx`: Top navigation bar.
- `components/Sidebar.jsx`: Left-hand navigation menu.
UI/UX DESIGN & VISUAL IDENTITY:
- **Style**: Modern, Professional, Trustworthy, slightly futuristic with data visualization focus.
- **Color Palette**: Dark theme primary for focus and data clarity. Accent colors for alerts and calls to action.
- Primary Background: `#121212` (Very Dark Gray)
- Secondary Background: `#1E1E1E` (Slightly Lighter Dark Gray)
- Primary Text: `#FFFFFF` (White)
- Secondary Text: `#A0A0A0` (Light Gray)
- Primary Accent (CTA, Active States): `#007AFF` (Vibrant Blue)
- Warning Alerts: `#FFA500` (Orange)
- Critical Alerts: `#FF3B30` (Red)
- Success/Info: `#34C759` (Green)
- **Typography**: Sans-serif. Use Inter or similar clean font. Headings should be bold and larger, body text readable.
- Headings: Inter Bold (e.g., 32px, 24px, 20px)
- Body: Inter Regular (e.g., 16px)
- **Layout**: Clean, card-based layout for dashboard widgets. Sidebar for navigation. Use 16px grid system.
- **Responsiveness**: Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Dashboard widgets reflow and stack vertically.
- **Visual Elements**: Use icons effectively (e.g., `react-icons`). Maps and charts should be clear and informative.
ANIMATIONS:
- **Page Transitions**: Subtle fade-in/out for Next.js App Router page transitions (can be implemented with Framer Motion or simple CSS).
- **Hover Effects**: Slight scale or background color change on interactive elements (buttons, links, table rows).
- **Loading States**: Use skeleton loaders or spinners (`@/components/ui/spinner`) for data fetching.
- **Subtle Parallax**: On the landing page for a modern feel.
- **Chart Animations**: Data visualizations should animate smoothly when loaded or updated.
EDGE CASES & ERROR HANDLING:
- **Authentication**: Redirects to login if not authenticated. Handle expired sessions gracefully.
- **Empty States**: Display informative messages and clear CTAs when no monitoring regions, alerts, or failover plans exist (e.g., 'You haven't added any monitoring regions yet. Click here to get started.').
- **Data Fetching Errors**: Show user-friendly error messages (e.g., 'Failed to load alerts. Please try again.') and provide retry options.
- **Form Validation**: Implement client-side and server-side validation for all forms (e.g., ensure region names are unique per user, metric values are valid).
- **API Rate Limits**: If integrating with external APIs, implement retry logic and handle rate limit errors.
- **Permissions**: Ensure users can only access and modify their own data.
- **Database Errors**: Gracefully handle potential database connection issues or query failures.
SAMPLE/MOCK DATA:
1. **Monitoring Region**: `{ id: 'uuid-1', userId: 'user-uuid', name: 'Main AWS Deployment', provider: 'AWS', region: 'us-east-1', isActive: true }`
2. **Monitoring Region**: `{ id: 'uuid-2', userId: 'user-uuid', name: 'EU Azure Hub', provider: 'Azure', region: 'westeurope', isActive: true }`
3. **Alert**: `{ id: 'uuid-3', userId: 'user-uuid', monitoringRegionId: 'uuid-1', eventDescription: 'Significant latency spike detected across multiple services.', eventType: 'Cloud Provider Status', severity: 'WARNING', occurredAt: '2024-07-26T10:00:00Z', status: 'ACTIVE' }`
4. **Alert**: `{ id: 'uuid-4', userId: 'user-uuid', monitoringRegionId: null, eventDescription: 'Reported cyberattack targeting major cloud infrastructure in the Middle East.', eventType: 'Cyber Attack', severity: 'CRITICAL', occurredAt: '2024-07-26T09:30:00Z', status: 'ACTIVE' }`
5. **Alert**: `{ id: 'uuid-5', userId: 'user-uuid', monitoringRegionId: 'uuid-2', eventDescription: 'Service outage reported for Azure West Europe region.', eventType: 'Cloud Provider Status', severity: 'CRITICAL', occurredAt: '2024-07-25T15:00:00Z', status: 'ACTIVE' }`
6. **Alert Threshold**: `{ id: 'uuid-6', userId: 'user-uuid', monitoringRegionId: 'uuid-1', metric: 'latency', operator: '>', value: '200ms', alertLevel: 'CRITICAL', isActive: true }`
7. **Alert Threshold**: `{ id: 'uuid-7', userId: 'user-uuid', monitoringRegionId: 'uuid-2', metric: 'service_outage', operator: '=', value: 'true', alertLevel: 'CRITICAL', isActive: true }`
8. **Failover Plan**: `{ id: 'uuid-8', userId: 'user-uuid', name: 'Europe Web Traffic Redirection', primaryTarget: 'Azure West Europe', failoverTarget: 'GCP Europe-West1', triggerConditions: { alertType: 'Cloud Provider Status', severity: 'CRITICAL', regionId: 'uuid-2' }, steps: [{ action: 'Update DNS Record', details: 'dns.example.com' }], isActive: false, isSimulated: true }`
9. **User**: `{ id: 'user-uuid', name: 'John Doe', email: 'john.doe@example.com', image: 'https://...' }`
10. **Session**: `{ sessionToken: '...', userId: 'user-uuid', expires: '2024-08-09T12:00:00Z' }`
TURKISH TRANSLATIONS:
- App Title: Resilience Shield
- Navbar: Gösterge Paneli (Dashboard), Ayarlar (Settings), Yedekleme Planları (Failover Plans), Çıkış Yap (Logout)
- Dashboard: Aktif Uyarılar (Active Alerts), İzlenen Bölgeler (Monitored Regions), Genel Tehdit Haritası (Global Threat Map)
- Settings: İzleme Bölgeleri (Monitoring Regions), Uyarı Eşikleri (Alert Thresholds), Profil (Profile)
- Monitoring Regions: Bölge Ekle (Add Region), Sağlayıcı (Provider), Bölge Adı (Region Name), Durum (Status), Aktif (Active), Pasif (Inactive)
- Alert Thresholds: Eşik Ekle (Add Threshold), Metrik (Metric), Operatör (Operator), Değer (Value), Uyarı Seviyesi (Alert Level), Bilgi (INFO), Uyarı (WARNING), Kritik (CRITICAL)
- Failover Plans: Plan Oluştur (Create Plan), Birincil Hedef (Primary Target), Yedek Hedef (Failover Target), Tetikleyici Koşullar (Trigger Conditions), Adımlar (Steps), Simüle Et (Simulate), Aktifleştir (Activate)
- Buttons: Kaydet (Save), İptal (Cancel), Ekle (Add), Düzenle (Edit), Sil (Delete), Onayla (Confirm)
- Placeholders/Labels: Lütfen sağlayıcıyı seçin (Please select a provider), Bölge adı girin (Enter region name), vs.
- Empty States: Henüz uyarı yok. (No alerts yet.)
- Success Messages: Bölge başarıyla eklendi. (Region added successfully.)
- Error Messages: Bir hata oluştu. Lütfen tekrar deneyin. (An error occurred. Please try again.)