You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13 中如何全局配置 SWRConfig?

在Next.js 13 App目录下全局配置SWRConfig的正确方式

你之前报错是因为<SWRConfig>是React组件,只能放在<body>标签内部的React上下文里,不能包裹<html>标签。正确的做法是把它放在<body>里,包裹所有需要共享SWR配置的内容,包括导航栏和页面子组件。

修改后的RootLayout代码如下:

import './globals.css';
import '@/styles/bootstrap.min.css'; // 保留原项目需要的bootstrap样式
import { Inter } from 'next/font/google';
import Navbar from '@/components/Navbar';
import { SWRConfig } from 'swr';

const inter = Inter({ subsets: ['latin'] });

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <SWRConfig
          value={{
            fetcher: async (url) => {
              const res = await fetch(url);
              // 处理非200-299状态码的请求
              if (!res.ok) {
                const error = new Error('An error occurred while fetching the data.');
                error.info = await res.json();
                error.status = res.status;
                throw error;
              }
              return res.json();
            },
          }}
        >
          <Navbar />
          <br />
          {children}
        </SWRConfig>
      </body>
    </html>
  );
}

这样配置后,App目录下所有页面和组件都会自动继承这个全局的SWR fetcher配置,无需重复编写错误处理逻辑。

内容的提问来源于stack exchange,提问作者Shivam Sangwan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 18:04:59