Build and maintain a full-stack economic analysis dashboard with Next.js 14 and Express.js
A comprehensive guide for building and maintaining a full-stack economic analysis dashboard with Next.js 14 App Router and Express.js backend.
This skill helps you develop a sophisticated economic data analysis platform featuring:
When initializing the project:
1. Create frontend with Next.js 14:
```bash
npx create-next-app@latest frontend --typescript --tailwind --app
```
2. Create backend with Express:
```bash
mkdir backend && cd backend
npm init -y
npm install express cors dotenv axios csv-parser
npm install --save-dev nodemon
```
3. Set up environment variables:
- Frontend `.env.local`: `NEXT_PUBLIC_API_URL=http://localhost:5000`
- Backend `.env`: `PORT=5000`, `NODE_ENV=development`, `CORS_ORIGIN=http://localhost:3000`
**Data Service Layer** (`backend/src/services/dataService.js`):
**Analysis Service** (`backend/src/services/analysisService.js`):
**API Routes** (`backend/src/routes/`):
**API Client** (`frontend/lib/api.ts`):
```typescript
// Create typed API functions for each endpoint
export async function fetchMarketData(params: MarketDataParams): Promise<MarketData> {
const response = await fetch(`${API_URL}/market-data?${new URLSearchParams(params)}`);
if (!response.ok) throw new Error('Failed to fetch data');
return response.json();
}
```
**Chart Components** (`frontend/components/charts/`):
**Page Structure** (`frontend/app/`):
**Data Visualization**:
1. Line charts for time series (GDP, S&P 500, Treasury yields)
2. Scatter plots for correlations
3. Heatmaps for multi-dimensional analysis
4. Implement zoom, tooltip, and legend interactions
**Statistical Analysis**:
1. Pearson correlation coefficient between any two metrics
2. 50-day and 200-day moving averages
3. Rolling volatility calculations
4. Auto-generate insights when correlation > 0.7 or volatility spike > 2σ
**Export Functionality**:
**TypeScript Practices**:
**Error Handling**:
```typescript
// Frontend
try {
const data = await fetchData();
setData(data);
} catch (error) {
console.error('Error fetching data:', error);
setError('Failed to load data. Please try again.');
} finally {
setLoading(false);
}
// Backend
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Internal server error' });
});
```
**Component Organization**:
**Frontend**:
**Backend**:
Add prominent disclaimer to all pages:
```typescript
<div className="bg-yellow-50 dark:bg-yellow-900 p-4 rounded-lg">
<p className="text-sm text-yellow-800 dark:text-yellow-200">
<strong>Disclaimer:</strong> This dashboard is for educational and research
purposes only. Data may be delayed or inaccurate. Not investment advice.
Past performance does not guarantee future results.
</p>
</div>
```
Before deploying, verify:
1. **Backend**: Add fetch function to `dataService.js`:
```javascript
export async function fetchNewMetric() {
try {
const response = await axios.get('API_URL');
return processData(response.data);
} catch (error) {
console.error('API failed, using CSV:', error);
return loadFromCSV('new-metric.csv');
}
}
```
2. **Create CSV fallback** in `backend/src/data/new-metric.csv`
3. **Add route** in `backend/src/routes/dataRoutes.js`:
```javascript
router.get('/new-metric', async (req, res) => {
try {
const data = await fetchNewMetric();
res.json({ data, source: 'API' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
```
4. **Update TypeScript types** in `frontend/types.ts`
5. **Create API client function** in `frontend/lib/api.ts`
6. **Build chart component** and add to appropriate page
1. Create component in `frontend/components/charts/NewChart.tsx`:
```typescript
import { ResponsiveContainer, LineChart, Line, XAxis, YAxis, Tooltip, Legend } from 'recharts';
interface NewChartProps {
data: DataPoint[];
loading?: boolean;
}
export function NewChart({ data, loading }: NewChartProps) {
if (loading) return <ChartSkeleton />;
if (!data.length) return <EmptyState message="No data available" />;
return (
<ResponsiveContainer width="100%" height={400}>
<LineChart data={data}>
<XAxis dataKey="date" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="value" stroke="#8884d8" />
</LineChart>
</ResponsiveContainer>
);
}
```
2. Use in page with lazy loading:
```typescript
const NewChart = dynamic(() => import('@/components/charts/NewChart'), { ssr: false });
```
1. Verify backend is running on port 5000: `curl http://localhost:5000/health`
2. Check `NEXT_PUBLIC_API_URL` in `.env.local`
3. Confirm CSV files exist in `backend/src/data/`
4. Open browser DevTools → Network tab to inspect failed requests
5. Check backend logs for error messages
1. Clear Next.js cache: `rm -rf .next`
2. Delete and reinstall dependencies: `rm -rf node_modules && npm install`
3. Fix TypeScript errors: `npm run build` (read error messages carefully)
4. Check for missing environment variables
1. Verify data format matches component props (check console.log)
2. Ensure no `undefined` values in data array
3. Confirm `ResponsiveContainer` has parent with defined height
4. Check Recharts version compatibility with Next.js 14
5. Disable SSR for chart component if hydration errors occur
```
project/
├── frontend/
│ ├── app/
│ │ ├── layout.tsx # Root layout with providers
│ │ ├── page.tsx # Homepage/dashboard
│ │ └── analysis/page.tsx # Analysis tools page
│ ├── components/
│ │ ├── charts/ # All chart components
│ │ ├── ui/ # Reusable UI components
│ │ └── layout/ # Header, footer, nav
│ ├── lib/
│ │ ├── api.ts # API client functions
│ │ └── utils.ts # Utility functions
│ └── types.ts # TypeScript interfaces
└── backend/
├── src/
│ ├── routes/ # Express routes
│ ├── services/ # Business logic
│ │ ├── dataService.js # Data fetching
│ │ └── analysisService.js # Statistical analysis
│ ├── data/ # CSV fallback files
│ └── index.js # Express app entry
└── .env # Backend environment vars
```
```bash
cd frontend && npm run dev # Start Next.js dev server (port 3000)
cd backend && npm run dev # Start Express with nodemon (port 5000)
cd frontend && npm run build # Build Next.js for production
cd backend && npm start # Start Express in production mode
npm run lint # ESLint check
npm run type-check # TypeScript check
```
1. **No Investment Advice**: Never include predictive language or recommendations
2. **Disclaimer Required**: Must be visible on every page with data visualization
3. **Data Accuracy**: Always show data source and last updated timestamp
4. **Error Resilience**: All external API calls must have CSV fallback
5. **Accessibility**: Charts must have text alternatives for screen readers
When asked to "add a new economic indicator to the dashboard":
1. Ask for data source API and CSV fallback location
2. Create fetch function in `dataService.js` with error handling
3. Add CSV file to `backend/src/data/`
4. Create Express route with query parameter validation
5. Define TypeScript interface in `types.ts`
6. Build API client function in `api.ts`
7. Create Recharts component with loading/error states
8. Add to appropriate page with lazy loading
9. Test with date range filtering
10. Verify CSV export functionality
This skill enables you to build production-ready economic analysis dashboards with proper error handling, performance optimization, and user experience considerations.
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/macro-market-analyzer-development/raw