Unfortunately, it's not supported in Next.js to disable prefetch globally.
The first workaround
- create a Babel plugin local to your project which adds
prefetch={false} everywhere we use <Link /> from 'next/link'.
/**
* Based on the docs at https://nextjs.org/docs/api-reference/next/link, the
* only way to disable prefetching is to make sure every <Link /> has <Link
* prefetch={false} />
*
* We don't want to create a wrapper Component or go around changing every
* single <Link />, so we use this Babel Plugin to add them in at build-time.
*/
module.exports = function (babel) {
const { types: t } = babel
return {
name: 'disable-link-prefetching',
visitor: {
JSXOpeningElement(path) {
if (path.node.name.name === 'Link') {
path.node.attributes.push(
t.jSXAttribute(
t.jSXIdentifier('prefetch'),
t.JSXExpressionContainer(t.booleanLiteral(false)),
),
)
}
},
},
}
}
- Add/modify ./.babelrc to load your local plugin:
{
"presets": ["next/babel"],
"plugins": ["./babel/disable-nextjs-link-prefetching"]
}
The Second workaround
Create a custom link component and use prefetch={false} for it and use it instead of using the next/link directly.
import Link from 'next/link'
export default function MyLink(props) {
// defaults prefetch to false if `prefetch` is not true
return <Link {...props} prefetch={props.prefetch ?? false}>
}
Resource