Reputation: 61
In most examples, to disable prefetching, they do so by disabling a specific link for prefetching, see the following example:
<Link href="/about" prefetch={false}>
<a>About us</a>
</Link>
I want to set prefetch to false for the whole project. Are there settings for this in the next.config.js file?
How should I do this?
Upvotes: 5
Views: 11921
Reputation: 2934
In addition to @Mina answer, note that disable prefetching on <Link>
component with prefetch props doesn't disable hover prefetching as mentionned in this github discussion: https://github.com/vercel/next.js/discussions/24437
As described on this discussion there is another workaround for globally disabling prefetching. This solution can be used for the entire website or only on a specific page.
To disable prefetching on entire website. Add following code to _app.tsx
const router = useRouter()
useEffect(() => {
router.prefetch = async () => { }
}, [router])
to disable prefetching on specific page add following code on your page
const router = useRouter()
useEffect(() => {
const prefetch = router.prefetch
router.prefetch = async () => { }
return () => { router.prefetch = prefetch }
}, [router])
Upvotes: 2
Reputation: 17019
Unfortunately, it's not supported in Next.js to disable
prefetch globally.
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)),
),
)
}
},
},
}
}
{
"presets": ["next/babel"],
"plugins": ["./babel/disable-nextjs-link-prefetching"]
}
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}>
}
Upvotes: 10