Learn Nuxt with a Collection of 100+ Tips!

shared

Use the shared/ directory to share functionality between the Vue app and the Nitro server.

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

The shared/ directory is available in Nuxt v3.14+.
Code in the shared/ directory cannot import any Vue or Nitro code.

Usage

Method 1: Using named export

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

Method 2: Using default export

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

Usage: You can now use auto-imported utility functions in .js, .ts and .vue files within your Vue app and the server/ directory.

If you have set compatibilityVersion: 4 in your nuxt.config.ts, you can use the auto-imported functions in the app/ directory. This is part of Nuxt's progressive compatibility features preparing for version 4.

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

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

Auto Imports

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.

The way shared/utils and shared/types auto-imports work and are scanned is identical to the composables/ and utils/ directories.
Read more in Docs > Guide > Directory Structure > Composables#how Files Are Scanned.
Directory Structure
-| 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.d.ts           # Auto-imported

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

// 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 in Docs > Guide > Concepts > Auto Imports.