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
Nuxt offers two options for your assets.
Nuxt
The public/ directory is used to serve your website's static assets.
Nuxt
Nuxt provides composables to handle data fetching within your application.
Was this page helpful?