Skip to content

Documentation inconsistency: useSWRMutation doesn't accept null key unlike useSWR #4217

@SL-YutoTakagi

Description

@SL-YutoTakagi

Description / Observed Behavior

The documentation states that useSWRMutation's key parameter is "same as mutate's key" which references "same as useSWR's key". However, unlike useSWR, useSWRMutation does not accept null as a key value and throws a console error when a falsy value is passed.

This is related to the unresolved #2456 where filter functions also don't work despite the documentation suggesting they should.

Documentation chain:

  1. useSWR API docs explicitly allow null: https://swr.vercel.app/docs/api

    key: a unique key string for the request (or a function / array / null)

  2. useSWRMutation docs state: https://swr.vercel.app/docs/mutation

    key: same as mutate's key

  3. mutate docs reference:

    key: same as useSWR's key. but the function will behave as a filter function

This documentation chain implies null should be acceptable for useSWRMutation, but it is not.

Expected Behavior

Based on the documentation and consistency with useSWR, I expected the following pattern to work without errors:

const shouldMutate = someCondition;
const { trigger } = useSWRMutation(
  shouldMutate ? '/api/user' : null,
  fetcher
);

This pattern is commonly used with useSWR for conditional fetching as documented here: https://swr.vercel.app/docs/conditional-fetching

Repro Steps / Code Example

import useSWR from 'swr';
import useSWRMutation from 'swr/mutation';

const fetcher = (url) => fetch(url).then(res => res.json());

function Component() {
  const condition = false;
  
  // This works fine with useSWR
  const { data } = useSWR(condition ? '/api/user' : null, fetcher);
  
  // This throws a console error with useSWRMutation
  const { trigger } = useSWRMutation(condition ? '/api/user' : null, fetcher);
  
  return <button onClick={() => trigger()}>Mutate;
}

Console error:
The error comes from the serialize function which is called in the mutation implementation but not properly handled for falsy values.

Root cause:

useSWRMutation calls serialize(key):
https://github.com/vercel/swr/blob/main/src/mutation/index.ts

The serialize function logs an error for falsy values:
https://github.com/vercel/swr/blob/main/src/_internal/utils/serialize.ts#L6

In contrast, useSWR handles falsy keys properly:
https://github.com/vercel/swr/blob/main/src/index/use-swr.ts#L213

Additional Context

SWR version: Latest (as of February 2026)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions