Tips for Common Pitfalls (`$fetch` vs `useFetch`, `public` vs `assets`)

Just a note for all, since these questions comes in here regularly. $fetch vs useFetch From the docs:
useFetch, useLazyFetch, useAsyncData and useLazyAsyncData only work during setup or Lifecycle Hooks https://nuxt.com/docs/getting-started/data-fetching#usefetch
So the use... composables only work inside your vue templates. So whenever you have an issue on this, try to use $fetch , and if it's not available import { $fetch } from 'ofetch' (this module is built into nuxt) public vs assets directory Docs: https://nuxt.com/docs/getting-started/assets You mainly want to use the public directory for your static files like fonts, images, videos, etc. They are being served at your project root and will not be modified by vite/webpack. https://nuxt.com/docs/guide/directory-structure/public The assets is only for files that will be processed by vite/webpack, and therefore also mostly need vite file handlers installed. This could be css files, svgs with nuxt-svgo or other files that are being processed on build. https://nuxt.com/docs/getting-started/assets#assets-directory Example: - you have a few woff2 font files, that can be served as-is. You would put them into public - you have some css files you want to include. You would put them into assets and include them with the nuxt.config css option. - you have some 5mb 4000x3000 jpegs: you can either use nuxt/image (where they can stay in public because they are being minified at runtime, not a build time), or you can use a custom vite plugin which would require them to be in assets .
Nuxt
Assets · Get Started with Nuxt
Nuxt offers two options for your assets.
Nuxt
public/ · Nuxt Directory Structure
The public/ directory is used to serve your website's static assets.
Nuxt
Data fetching · Get Started with Nuxt
Nuxt provides composables to handle data fetching within your application.
2 Replies
Mads
Mads2y ago
I have some questions as well that I was hoping you could clear up for me: When prerendering pages:
nitro: {
prerender: {
crawlLinks: true,
routes: ["/"],
ignore: ["/tak", "/konfiguration", "/checkout"],
},
}
nitro: {
prerender: {
crawlLinks: true,
routes: ["/"],
ignore: ["/tak", "/konfiguration", "/checkout"],
},
}
1. I don't need those pages to be calling my fetch functions on each visit. They should be in their nature "prerendered". What am I misunderstanding here? 2. In Nuxt 2 we had this wonderful thing called Smart Prefetching, where when a nuxt link is visible, it would fetch the data from the respective links. Is that still a thing, it seems to me it only fetches when clicking. Images as well.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server