Registry / http-networking / swr
library2.4.1jsnpmunverified

SWR is a lightweight and performant React Hooks library for remote data fetching, currently at version 2.4.1. It implements the 'stale-while-revalidate' cache invalidation strategy, popularized by HTTP RFC 5861, to provide an always-fresh and responsive user interface. Maintained by Vercel, SWR ensures components receive a continuous stream of data updates automatically. It offers robust features like built-in caching, request deduplication, real-time revalidation on focus/network recovery, polling, pagination, local mutation for optimistic UI, smart error retry, and comprehensive TypeScript support. Its predictable release cadence, with frequent minor updates and patches, ensures ongoing stability and feature enhancements. Key differentiators include its simplicity with a single `useSWR` hook, strong focus on performance and developer experience, and broad support for modern React features like Suspense.

npm install swr
INSTALL
IMPORT
SIG · SWR
S
swr
http-networkingjavascriptv2.4.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

useSWR
import useSWR from 'swr'
import { useSWR } from 'swr'
The primary data fetching hook, `useSWR`, is a default export. Attempting to destructure it as a named export will result in an error.
SWRConfig
import { SWRConfig } from 'swr'
import SWRConfig from 'swr'
`SWRConfig` is a named export used to provide global configurations to all `useSWR` hooks within its scope. Do not attempt to import it as a default export.
useSWRImmutable
import { useSWRImmutable } from 'swr'
import useSWRImmutable from 'swr'
`useSWRImmutable` is a named export, functioning similarly to `useSWR` but for data that should not revalidate. Incorrectly importing it as default will cause issues.
Key
import type { Key } from 'swr'
import { Key } from 'swr'
When importing types like `Key`, `Fetcher`, or `SWRResponse`, ensure to use `import type` for better type safety and to prevent accidental runtime imports.

Demonstrates basic data fetching using `useSWR` with a custom `fetcher` function, handling loading and error states for a user profile.

import useSWR from 'swr'; const fetcher = async (url) => { const res = await fetch(url); 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(); }; function UserProfile() { // In a real application, you might use an environment variable for the base URL const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? 'https://api.example.com'; const userId = '123'; // Example user ID const { data, error, isLoading } = useSWR(`${API_BASE_URL}/users/${userId}`, fetcher); if (error) return <div>Failed to load user data: {error.message}</div>; if (isLoading) return <div>Loading user profile...</div>; return ( <div> <h1>User Profile</h1> <p>Name: {data.name}</p> <p>Email: {data.email}</p> </div> ); } // Example of how to render it (e.g., in a React component tree) // function App() { // return <UserProfile />; // } // export default App;
Debug
Known issues
breakingSWR v2 introduced breaking changes related to the return shape of the `useSWR` hook, error handling, and `mutate` API. Specifically, `isValidating` was replaced with `isLoading` for initial data fetching state, and the `mutate` function no longer accepts `shouldRevalidate` as a direct boolean argument but as part of an options object.
fix
Review the SWR v2 migration guide on the official documentation. Update `isValidating` to `isLoading` for initial load checks. Adjust `mutate` calls to `mutate(key, data, { revalidate: false })` for preventing revalidation.
affects: >=2.0.0
breakingSWR transitioned to an ESM-first package distribution starting from v2. While CJS bundles are still provided for backward compatibility, ESM is the recommended way to import. Users with older tooling or specific CommonJS setups might face issues.
fix
Ensure your project is configured to handle ESM imports, especially for bundlers like Webpack or Rollup. For Node.js, ensure `"type": "module"` in `package.json` or use `.mjs` extensions. If strictly using CommonJS, explicit `require('swr/dist/index.cjs')` might be necessary, though not officially recommended.
affects: >=2.0.0
gotchaWhen using `useSWRImmutable`, global `refreshInterval` settings might still trigger revalidations. This can lead to unexpected data refreshes for data intended to be static.
fix
Ensure `useSWRImmutable` explicitly overrides any global `refreshInterval` via its options: `useSWRImmutable(key, fetcher, { refreshInterval: 0 })`. Version 2.4.0 and later should correctly handle this override, but explicit setting provides clarity and robustness.
affects: >=2.4.0
breakingMultiple critical RCE (Remote Code Execution) vulnerabilities (CVE-2025-55182, CVE-2025-55183, CVE-2025-55184) were identified and patched in version 2.3.8. These vulnerabilities could allow an attacker to execute arbitrary code.
fix
Immediately upgrade SWR to version 2.3.8 or newer to patch these critical security vulnerabilities. Review any potentially affected deployments for signs of compromise.
affects: <2.3.8
gotchaWhen `useSWR` is enabled in Suspense mode (`suspense: true`), the `data` property will never be `undefined` (it will throw a Promise instead). Components must be wrapped in `<Suspense>` boundary. Misunderstanding this can lead to 'cannot read properties of undefined' errors.
fix
Always wrap components using `useSWR` with `suspense: true` in a `<Suspense>` boundary. Remove `if (isLoading)` or `if (!data)` checks as they are not needed; the component will only render once data is available. Handle errors using `error` boundary components.
affects: >=1.0.0
Errors
Common errors & fixes
Error: useSWR is not a function
Attempting to import `useSWR` as a named export when it is a default export.
fix
Change your import statement from `import { useSWR } from 'swr'` to `import useSWR from 'swr'`.
TypeError: Cannot read properties of undefined (reading 'name') at Profile
Attempting to access `data` before it's loaded, especially when not using Suspense, or when `data` is `undefined` due to an error or initial loading state.
fix
Always check for `isLoading` or `error` before accessing `data`. Example: `if (isLoading) return <div>loading...</div>; if (error) return <div>failed to load</div>; return <div>hello {data.name}!</div>`.
Failed to compile. Module parse failed: Cannot assign to read only property 'exports' of object '#<Object>'
Mixing CommonJS `require()` with an ESM-first library like SWR, or incorrect bundler configuration for ESM modules.
fix
Ensure your project uses `import` statements for SWR. If using Node.js, confirm `"type": "module"` is set in your `package.json` or use `.mjs` extensions for files importing SWR. Check bundler configuration (e.g., Webpack, Rollup) to correctly resolve ESM modules.
Type 'undefined' is not assignable to type '...' when using data from useSWR with TypeScript and Suspense is enabled.
When `suspense: true` is enabled, SWR guarantees `data` will always be defined at the component render point, but TypeScript might still infer it as `data | undefined` without proper configuration.
fix
Configure TypeScript by ensuring `"compilerOptions": { "exactOptionalPropertyTypes": true }` is not set to `false` if it conflicts. More practically, if `suspense: true` is used, TypeScript should infer `data` as non-nullable. If it doesn't, ensure your TypeScript version is compatible and explicitly assert type if necessary (e.g., `data!.name`), though this should ideally be avoided.
Upgrade
Version history
2.4.1latest on npm
Audit
Dependencies
reactrequiredSWR is a React Hooks library and requires a compatible version of React to function.
Agent activity
14 hits · last 30 days
node
12
OpenAI (training)
1
Resources
swr — npm install swr · libregistry