Back to Nuxt

shared

docs/2.directory-structure/1.shared.md

4.4.42.6 KB
Original Source

The shared/ directory allows you to share code that can be used in both the Vue app and the Nitro server.

::note The shared/ directory is available in Nuxt v3.14+. ::

::important Code in the shared/ directory cannot import any Vue or Nitro code. ::

:video-accordion{title="Watch a video from Vue School on sharing utils and types between app and server" videoId="nnAR-MO3q5M"}

Usage

Method 1: Named export

ts
export const capitalize = (input: string) => {
  return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
}

Method 2: Default export

ts
export default function (input: string) {
  return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
}

You can now use auto-imported utilities in your Nuxt app and server/ directory.

vue
<script setup lang="ts">
const hello = capitalize('hello')
</script>

<template>
  <div>
    {{ hello }}
  </div>
</template>
ts
export default defineEventHandler((event) => {
  return {
    hello: capitalize('hello'),
  }
})

How Files Are Scanned

Only files in the shared/utils/ and shared/types/ directories will be auto-imported. Files nested within subdirectories of these directories will not be auto-imported unless you add these directories to imports.dirs and nitro.imports.dirs.

::tip The way shared/utils and shared/types auto-imports work and are scanned is identical to the app/composables/ and app/utils/ directories. ::

:read-more{to="/docs/4.x/directory-structure/app/composables#how-files-are-scanned"}

bash
-| shared/
---| capitalize.ts        # Not auto-imported
---| formatters
-----| lower.ts           # Not auto-imported
---| utils/
-----| lower.ts           # Auto-imported
-----| formatters
-------| upper.ts         # Not auto-imported
---| types/
-----| bar.ts             # Auto-imported

Any other files you create in the shared/ folder must be manually imported using the #shared alias (automatically configured by Nuxt):

ts
// For files directly in the shared directory
import capitalize from '#shared/capitalize'

// For files in nested directories
import lower from '#shared/formatters/lower'

// For files nested in a folder within utils
import upper from '#shared/utils/formatters/upper'

This alias ensures consistent imports across your application, regardless of the importing file's location.

:read-more{to="/docs/4.x/guide/concepts/auto-imports"}