Skip to content

Images and File Uploads in Nuxt

Optimize images with Nuxt Image and TwicPics, and store file uploads locally or in S3-compatible storage such as Cloudflare R2 with type and size checks.

Nuxt Starter Kit uses Nuxt Image module to resize and transform your images using the TwicPics CDN.

Image Provider

The starter kit uses TwicPics as the image provider for CDN delivery. TwicPics provides:

  • Automatic image optimization
  • Responsive images
  • Format conversion (WebP, AVIF)
  • Lazy loading support

Configuration

Images are configured in apps/web/layers/core/nuxt.config.ts:

export default defineNuxtConfig({
  image: {
    provider: 'twicpics',
    twicpics: {
      baseURL: siteConfig.imageProviderUrl
    }
  }
})

The imageProviderUrl is defined in packages/site-config/siteConfig.ts.

Usage

Use the <NuxtImg> component for optimized images:

<template>
  <NuxtImg
    src="landing-page/hero.png"
    alt="Hero image"
    width="1200"
    height="600"
    loading="lazy"
  />
</template>

Static Images

Place static images in the public/ directory:

public/
  ├── landing-page/
  │   ├── hero.png
  │   └── features.png
  └── docs/
      └── screenshots/

Image Optimization Tips

  1. Use appropriate formats: WebP for web, AVIF for modern browsers
  2. Lazy loading: Add loading="lazy" for below-the-fold images
  3. Responsive images: Use sizes and srcset attributes
  4. Compress before upload: Pre-compress large images before adding to repository

File Storage

File uploads live in the optional storage layer (apps/web/layers/storage). It stores files in S3-compatible storage or on the local disk and keeps their metadata in the file table: file name, path, size, MIME type, storage provider, upload date and the uploading user. It also provides the avatar upload in the profile settings.

Don't need uploads? Delete apps/web/layers/storage, run pnpm db:generate and remove @aws-sdk/client-s3 and ioredis from apps/web/package.json. See Layers.

Configuration

Set the storage values in apps/web/.env:

NUXT_PRIVATE_STORAGE_PROVIDER=s3 # s3 or local (default)
NUXT_PRIVATE_STORAGE_UPLOAD_DIR= # optional folder prefix

# when NUXT_PRIVATE_STORAGE_PROVIDER is local
NUXT_PRIVATE_STORAGE_LOCAL_PUBLIC_PATH=/uploads

# when NUXT_PRIVATE_STORAGE_PROVIDER is s3
NUXT_PRIVATE_STORAGE_S3_ACCESS_KEY_ID=your-access-key-id
NUXT_PRIVATE_STORAGE_S3_SECRET_ACCESS_KEY=your-secret-access-key
NUXT_PRIVATE_STORAGE_S3_BUCKET_NAME=your-bucket-name
NUXT_PRIVATE_STORAGE_S3_REGION=us-east-1 # optional, defaults to us-east-1
NUXT_PRIVATE_STORAGE_S3_ENDPOINT= # optional, for S3-compatible providers
NUXT_PRIVATE_STORAGE_S3_PUBLIC_URL= # optional, defaults to the AWS bucket URL

# optional: upload rules
NUXT_PRIVATE_STORAGE_ALLOWED_MIME_TYPES=
NUXT_PRIVATE_STORAGE_MAX_FILE_SIZE=

# optional: enables the upload rate limit
NUXT_PRIVATE_REDIS_URL=

Allowed File Types and Size

The upload API detects the file type from the file content. It ignores the MIME type and file name the client sends, and stores the detected type and extension. This way an HTML or SVG file sent as image/png can't be stored and served.

  • Only PNG, JPEG, GIF, WebP, AVIF and PDF can be uploaded. Every other type, including SVG, HTML and CSV, returns 415, even if NUXT_PRIVATE_STORAGE_ALLOWED_MIME_TYPES lists it.
  • NUXT_PRIVATE_STORAGE_ALLOWED_MIME_TYPES is a comma-separated list from these types. Without it, only the image types are allowed. Add application/pdf to allow PDFs.
  • NUXT_PRIVATE_STORAGE_MAX_FILE_SIZE is the limit in bytes. Without it, the limit is 10 MB. Larger files return 413.

Upload Rate Limit

When NUXT_PRIVATE_REDIS_URL is set, each user can upload 100 files per minute. Further uploads return 429. Without Redis, there is no upload limit. Rejected files don't count.

Uploading Files

The layer has these API routes, all of them require a signed-in user:

RouteWhat it does
POST /api/storage/uploadUpload one file as multipart form data (field file)
GET /api/storage/listList files
GET /api/storage/:idGet a file
DELETE /api/storage/:idDelete a file

On the client, use the useFileStorage() composable:

<script setup lang="ts">
const logger = useLogger('upload')
const { error, uploading, uploadToServer } = useFileStorage({
  onSuccess: file => logger.info('Uploaded', file.path),
})

async function onChange (event: Event) {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (file)
    await uploadToServer(file)
}
</script>

<template>
  <div>
    <input
      type="file"
      accept="image/*"
      :disabled="uploading"
      @change="onChange"
    >
    <p v-if="error">
      {{ error }}
    </p>
  </div>
</template>

On the server, getStorageProvider() and useServerFileStorage() upload, read and delete files with the configured provider. See apps/web/layers/storage/server/api/storage/upload.post.ts for an example.

AWS S3 Setup

  1. Create an S3 Bucket:
    • Go to AWS S3 Console
    • Create a new bucket with a unique name
    • Configure bucket settings (versioning, encryption, etc.)
  2. Create IAM User:
    • Go to IAM Console
    • Create a new user with programmatic access
    • Attach a policy with S3 permissions
    • Save the Access Key ID and Secret Access Key

For production, use a restrictive policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:GetObject",
        "s3:DeleteObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::your-bucket-name/*",
        "arn:aws:s3:::your-bucket-name"
      ]
    }
  ]
}

S3-Compatible Providers

Set NUXT_PRIVATE_STORAGE_S3_ENDPOINT to use an S3-compatible provider. The kit then uses path-style URLs, which these providers usually need:

  • Cloudflare R2 - no egress fees
  • DigitalOcean Spaces
  • Backblaze B2
  • MinIO - self-hosted

Set NUXT_PRIVATE_STORAGE_S3_PUBLIC_URL to the public URL of your bucket or CDN.

Storage Best Practices

  1. Scan for malware - Implement virus scanning for user uploads if your users share files
  2. Organize files - The kit stores files as {uploadDir}/{userId}/{YYYY-MM-DD}/{uuid}.{ext}
  3. Set lifecycle policies - Automatically delete or archive old files
  4. Enable versioning - Protect against accidental deletions
  5. Monitor costs - Set up alerts for your storage usage