Skip to content
문서
Next.js SSG 및 SSR

Usage with Next.js

App Router

Server Components

In Next.js App Router, all components are React Server Components (RSC) by default. You could only import the key serialization APIs from SWR in RSC.

app/page.tsx
import { unstable_serialize } from 'swr' // ✅ Available in server components
import { unstable_serialize as infinite_unstable_serialize } from 'swr/infinite' // ✅ Available in server components
🚫

You could not import any other APIs from SWR since they are not available in RSC.

app/page.tsx
import useSWR from 'swr' // ❌ This is not available in server components

Client Components

You can mark your components with 'use client' directive or import SWR from client components, both ways will allow you to use the SWR client data fetching hooks.

app/page.tsx
'use client'
import useSWR from 'swr'
export default Page() {
  const { data } = useSWR('/api/user', fetcher)
  return <h1>{data.name}</h1>
}

If you need to use SWRConfig to configure global settings in server components layout or page, creating a separate provider client component to setup the provider and configuration then use it in the server component pages.

app/swr-provider.tsx
'use client';
import { SWRConfig } from 'swr'
export const SWRProvider = ({ children }) => {
  return <SWRConfig>{children}</SWRConfig>
};
app/page.tsx
// This is still a server component
import { SWRProvider } from './swr-provider'
export default Page() {
  return (
    <SWRProvider>
      <h1>hello SWR</h1>
    </SWRProvider>
  )
}

Client Side Data Fetching

If your page contains frequently updating data, and you don’t need to pre-render the data, SWR is a perfect fit and no special setup needed: just import useSWR and use the hook inside any components that use the data.

Here’s how it works:

  • First, immediately show the page without data. You can show loading states for missing data.
  • Then, fetch the data on the client side and display it when ready.

This approach works well for user dashboard pages, for example. Because a dashboard is a private, user-specific page, SEO is not relevant and the page doesn’t need to be pre-rendered. The data is frequently updated, which requires request-time data fetching.

Pre-rendering with Default Data

If the page must be pre-rendered, Next.js supports 2 forms of pre-rendering (opens in a new tab): Static Generation (SSG) and Server-side Rendering (SSR).

Together with SWR, you can pre-render the page for SEO, and also have features such as caching, revalidation, focus tracking, refetching on interval on the client side.

You can use the fallback option of SWRConfig to pass the pre-fetched data as the initial value of all SWR hooks.

For example with getStaticProps:

 export async function getStaticProps () {
  // `getStaticProps` is executed on the server side.
  const article = await getArticleFromAPI()
  return {
    props: {
      fallback: {
        '/api/article': article
      }
    }
  }
}
 
function Article() {
  // `data` will always be available as it's in `fallback`.
  const { data } = useSWR('/api/article', fetcher)
  return <h1>{data.title}</h1>
}
 
export default function Page({ fallback }) {
  // SWR hooks inside the `SWRConfig` boundary will use those values.
  return (
    <SWRConfig value={{ fallback }}>
      <Article />
    </SWRConfig>
  )
}

The page is still pre-rendered. It's SEO friendly, fast to response, but also fully powered by SWR on the client side. The data can be dynamic and self-updated over time.

💡

The Article component will render the pre-generated data first, and after the page is hydrated, it will fetch the latest data again to keep it refresh.

Complex Keys

useSWR can be used with keys that are array and function types. Utilizing pre-fetched data with these kinds of keys requires serializing the fallback keys with unstable_serialize.

import useSWR, { unstable_serialize } from 'swr'
 
export async function getStaticProps () {
  const article = await getArticleFromAPI(1)
  return {
    props: {
      fallback: {
        // unstable_serialize() array style key
        [unstable_serialize(['api', 'article', 1])]: article,
      }
    }
  }
}
 
function Article() {
  // using an array style key.
  const { data } = useSWR(['api', 'article', 1], fetcher)
  return <h1>{data.title}</h1>
}
 
export default function Page({ fallback }) {
  return (
    <SWRConfig value={{ fallback }}>
      <Article />
    </SWRConfig>
  )
}