Auth & Basic Usage

Learn how to authenticate and integrate the easyCDN Dropzone component into your React application with practical examples.

Authentication

easyCDN uses two types of API keys for authentication:

Public Key

Safe for client-side use, used in React components

Secret Key

Server-side only, never expose in client code

Security Warning

Never use your secret key in client-side code. Secret keys should only be used in server-side environments where they cannot be accessed by end users.

Getting Your API Keys

To get your API keys:

  1. 1
    Log in to your easyCDN dashboard
  2. 2
    Navigate to your project settings
  3. 3
    Go to the "Developers" section
  4. 4
    Copy your Public Key for client-side use

Basic Usage

The simplest way to add file upload functionality to your React app is with the Dropzone component:

tsx
'use client'
import { Dropzone } from '@easycdn/react'

export default function MyUploadPage() {
  return (
    <Dropzone
      publicKey={process.env.NEXT_PUBLIC_EASYCDN_PUBLIC_KEY}
      onUploadComplete={({ tempId, previewUrl }) => {
        console.log('Upload complete:', { tempId, previewUrl })
        // make sure to persist this asset in the backend, see Node.js SDK
      }}
    />
  )
}

Handling Upload Results

When a file upload completes, you'll receive important information in the onUploadComplete callback:

tsx
import { Dropzone } from '@easycdn/react'

export default function UploadWithHandling() {
  const handleUploadComplete = ({ tempId, previewUrl, expiresAt }, file) => {
    console.log('File uploaded:', file.name)
    console.log('Temp ID:', tempId)
    console.log('Preview URL:', previewUrl)
    console.log('Expires at:', expiresAt)
    
    // Save the tempId to your database or state
    // Use previewUrl to show immediate preview
  }

  return (
    <Dropzone
      publicKey={process.env.NEXT_PUBLIC_EASYCDN_PUBLIC_KEY}
      onUploadComplete={handleUploadComplete}
    />
  )
}

Common Configuration Options

Customize the Dropzone behavior with these commonly used props:

File Size and Type Restrictions

tsx
<Dropzone
  publicKey={process.env.NEXT_PUBLIC_EASYCDN_PUBLIC_KEY}
  maxSize={1024 * 1024 * 10} // 10MB limit
  maxFiles={5} // Allow up to 5 files
  acceptedFileTypes={['image/*', '.pdf', '.docx']}
  onUploadComplete={handleUploadComplete}
/>

Visual Customization

tsx
<Dropzone
  publicKey={process.env.NEXT_PUBLIC_EASYCDN_PUBLIC_KEY}
  showPreview={true} // Show image previews
  darkMode={true} // Dark theme
  compact={true} // Compact file list
  className="my-custom-dropzone"
  onUploadComplete={handleUploadComplete}
/>

Full-Featured Example

Here's a complete example showing common use cases and best practices:

tsx
'use client'
import { Dropzone } from '@easycdn/react'
import { useState } from 'react'
import { toast } from 'sonner'

export default function FileUploadComponent() {
  const [uploadedFiles, setUploadedFiles] = useState([])

  const handleUploadComplete = ({ tempId, previewUrl, expiresAt }, file) => {
    // Add to local state
    setUploadedFiles(prev => [...prev, {
      id: tempId,
      name: file.name,
      url: previewUrl,
      expiresAt
    }])

    // Show success message
    toast.success(`${file.name} uploaded successfully!`)

    // TODO: Send tempId to your backend to persist the file
    // persistFile(tempId)
  }

  const handleUploadError = (error, file) => {
    if (error.status === 401) {
      toast.error('Authentication failed. Please check your API key.')
    } else if (error.status === 403) {
      toast.error('Access denied. Please check your permissions.')
    } else {
      toast.error(`Upload failed: ${error.message}`)
    }
  }

  return (
    <div className="max-w-2xl mx-auto p-6">
      <h2 className="text-2xl font-semibold mb-6">Upload Your Files</h2>
      
      <Dropzone
        publicKey={process.env.NEXT_PUBLIC_EASYCDN_PUBLIC_KEY}
        maxSize={1024 * 1024 * 50} // 50MB
        maxFiles={10}
        acceptedFileTypes={['image/*', 'video/*', '.pdf']}
        showPreview={true}
        onUploadComplete={handleUploadComplete}
        onUploadError={handleUploadError}
        className="mb-8"
      />

      {/* Display uploaded files */}
      {uploadedFiles.length > 0 && (
        <div className="mt-8">
          <h3 className="text-lg font-semibold mb-4">
            Uploaded Files ({uploadedFiles.length})
          </h3>
          <div className="grid gap-4">
            {uploadedFiles.map((file) => (
              <div key={file.id} className="flex items-center p-4 border rounded-lg">
                <div className="flex-1">
                  <p className="font-medium">{file.name}</p>
                  <p className="text-sm text-gray-600">ID: {file.id}</p>
                </div>
                <a 
                  href={file.url} 
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="text-blue-600 hover:text-blue-700"
                >
                  View
                </a>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

Environment Variables

Store your API keys as environment variables for better security:

N
Next.js Setup

Create a .env.local file in your project root:

bash
# .env.local
NEXT_PUBLIC_EASYCDN_PUBLIC_KEY=pk-your-public-key-here

R
Create React App Setup

bash
# .env
REACT_APP_EASYCDN_PUBLIC_KEY=pk-your-public-key-here

V
Vite Setup

bash
# .env
VITE_EASYCDN_PUBLIC_KEY=pk-your-public-key-here

Security Best Practices

  • Always use environment variables for API keys
  • Add .env* files to your .gitignore
  • Only use your public key in client-side code
  • Always use HTTPS in production