Skip to content

Instantly share code, notes, and snippets.

@sirius0486
Created March 19, 2025 17:42
Show Gist options
  • Save sirius0486/aca539fefdc28bcb0f75b2d62a5060f4 to your computer and use it in GitHub Desktop.
Save sirius0486/aca539fefdc28bcb0f75b2d62a5060f4 to your computer and use it in GitHub Desktop.
access_control
// middleware.ts
import { NextResponse } from 'next/server'
export function middleware(request) {
const { pathname } = request.nextUrl
const userInfoCookie = request.cookies.get('user_info')?.value
// 解析用户信息(需错误处理)
const user = userInfoCookie ? JSON.parse(userInfoCookie) : null
// 保护管理员路由
if (pathname.startsWith('/admin') && user?.role !== 'admin') {
return NextResponse.redirect(new URL('/unauthorized', request.url))
}
// 保护登录后才能访问的页面
if (pathname.startsWith('/dashboard') && !user) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}
//
// app/layout.tsx
import { cookies } from 'next/headers'
export default function RootLayout({ children }) {
const cookieStore = cookies()
const userInfo = cookieStore.get('user_info')?.value || '{}'
const user = JSON.parse(userInfo) // 实际项目中应添加错误处理
return (
<html>
<body>
<Sidebar user={user} />
{children}
</body>
</html>
)
}
// sidebar.tsx
'use client'
export default function Sidebar({ user }) {
return (
<div className="sidebar">
{user?.role === 'admin' && (
<a href="/admin" className="admin-link">管理后台</a>
)}
{user ? (
<>
<a href="/dashboard">仪表盘</a>
<a href="/profile">个人中心</a>
</>
) : (
<a href="/login">登录</a>
)}
</div>
)
}
// 3.
// app/admin/page.js
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export default function AdminPage() {
const userInfo = cookies().get('user_info')?.value
// 服务端直接跳转
if (!userInfo || JSON.parse(userInfo).role !== 'admin') {
redirect('/unauthorized')
}
return <div>管理员专属页面</div>
}
//4.
// app/page.tsx
export default async function Page() {
// 直接使用 async/await 获取数据
const response = await fetch('https://api.example.com/data')
const data = await response.json()
return (
<div>
<h1>服务端获取数据示例</h1>
<ul>
{data.map((item: any) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment