-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware-edge-functions.js
More file actions
65 lines (58 loc) · 1.66 KB
/
middleware-edge-functions.js
File metadata and controls
65 lines (58 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* 📘 Topic: Next.js Middleware & Edge Functions
*
* Middleware in Next.js runs **before** a request is completed.
* You can:
* - Authenticate users
* - Redirect conditionally
* - Add headers
* - Rewrite paths
*
* ⚙️ It runs at the Edge — super fast & globally distributed.
*/
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
/**
* 🔹 Middleware function
* This runs before rendering any route (in specified matchers or root level)
*/
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const token = req.cookies.get('token')?.value;
// 🔒 Redirect unauthenticated users
if (pathname.startsWith('/dashboard') && !token) {
const loginUrl = new URL('/login', req.url);
return NextResponse.redirect(loginUrl);
}
// 🌍 Add Geo-based headers (e.g., for A/B testing or i18n)
const country = req.geo?.country || 'US';
const res = NextResponse.next();
res.headers.set('x-country', country);
return res;
}
/**
* 🔍 Limit the paths this middleware runs on
*/
export const config = {
matcher: ['/dashboard/:path*', '/profile/:path*'],
};
/**
* 🧠 Key Concepts:
* - Runs on Edge (no cold starts, fast)
* - Zero latency for redirects or blocking
* - Can inspect cookies, headers, geolocation
* - Doesn't have access to DOM or response body
*
* 🚫 Limitations:
* - No full access to req.body
* - No DB queries directly (use API routes for that)
*
* ✅ Use cases:
* - Auth protection
* - Locale routing
* - Feature flags
* - Bot blocking / rate limiting
*
* 📁 Where to create:
* Create `middleware.ts` or `middleware.js` in project root.
*/