修复 Sanity Studio "Tool not found: studio" 错误
访问 /studio 时报 "Tool not found: studio"?根因是 sanity.config.ts 缺少 basePath 配置,导致 Studio 路由器无法正确解析工具名。
背景
在完成 Sanity Studio 的后台接入后,访问 /studio 路径时浏览器控制台抛出了一个错误:
Error: Tool not found: studio看起来像是某个工具插件名对不上,但实际上根因在于 Studio 路由器不知道自己被挂载在哪个路径下。
为什么会发生这个错误
Sanity Studio v3 内部有一套基于 history API 的客户端路由。它在启动时会读取 basePath 来确定自己被挂载在哪个 URL 段,再据此解析工具名(如 desk、presentation 等)。
如果 sanity.config.ts 没有显式声明 basePath,Studio 默认认为自己在根路径 /。但在 Next.js App Router 中,Studio 被放在 app/studio/[[...tool]]/page.tsx,实际挂载路径是 /studio。两者不一致,路由器就无法从 URL 中正确解析出工具名,于是报出 "Tool not found: studio"——这里的 studio 其实是它误把路径段当成了工具名来解析。
修复方法
只需要在 sanity.config.ts 里加一行 basePath:
import { defineConfig } from 'sanity'
import { structureTool } from 'sanity/structure'
export default defineConfig({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!,
basePath: '/studio', // ← 这一行是关键
plugins: [
structureTool(),
],
})basePath 的值必须与 Next.js 路由目录一致。如果你把 Studio 放在 app/cms/[[...tool]],那就写 /cms。
验证
保存后重启开发服务器,再次访问 /studio,错误消失,Studio 界面正常加载,左侧工具栏的 Desk、Structure 等工具也全部可以正常切换。
总结
这个错误的本质是 Sanity Studio 客户端路由的挂载路径与实际 URL 不匹配。一行 basePath 配置解决了全部问题。如果你使用了多个 workspace,每个 workspace 都需要独立配置自己的 basePath。