Next.js 13中带'use client'的Sanity Studio仍在服务端渲染求助
解决Next.js app路由下Sanity Studio加载卡住且仍服务端渲染的问题
针对你遇到的/admin路由加载Sanity Studio一直转圈、添加"use client"后组件仍在服务端渲染的问题,试试以下几个排查和解决步骤:
1. 确认sanity.config的正确性
Sanity配置文件必须是客户端兼容的,确保你用defineConfig正确导出配置,且必须设置basePath: '/admin'——这是Next.js集成Sanity Studio的关键,缺失会导致Studio内部路由异常,表现为页面一直加载:
// sanity.config.js import { defineConfig } from 'sanity' import { structureTool } from 'sanity/structure' export default defineConfig({ projectId: '你的项目ID', dataset: '你的数据集名称', basePath: '/admin', plugins: [structureTool()], // 其他配置项 })
同时确保配置文件中没有包含服务端专属代码(比如仅服务端可用的API调用、模块)。
2. 用动态导入强制禁用SSR
如果"use client"指令没生效,改用Next.js的动态导入并明确禁用服务端渲染,确保组件只在客户端加载:
// app/admin/[[...index]]/page.tsx import dynamic from 'next/dynamic' const Studio = dynamic(() => import('@/src/components/Studio/Studio'), { ssr: false, loading: () => <div>加载Sanity Studio...</div> }) const Admin = () => { return <Studio /> } export default Admin
3. 检查版本兼容性
确保next-sanity和next版本匹配,执行以下命令更新到最新稳定版:
npm install next-sanity@latest next@latest
版本不兼容可能导致客户端渲染逻辑失效。
4. 验证路由结构
确认你的文件夹结构完全正确:
app/ └── admin/ └── [[...index]]/ └── page.tsx
[[...index]]是catch-all路由,必须严格按照这个层级创建,否则Sanity Studio的内部路由无法被正确捕获。
5. 清除缓存并重启服务
缓存可能保留旧的编译结果,执行以下操作:
- 删除
.next文件夹 - 重启开发服务器:
npm run dev
6. 排查Next.js配置
检查next.config.js中是否有影响客户端渲染的配置,比如output: 'export'(静态导出),如果是静态导出,需要额外配置trailingSlash: true,并确保Sanity Studio的basePath正确。
内容的提问来源于stack exchange,提问作者BlackH3art
相关产品推荐
相关产品推荐

