Skip to main content

Uppy 4.0 is here: TypeScript rewrite, Google Photos, React hooks, and much more.

React Router

Integration guide for the React components for the Uppy UI plugins and hooks.

tip

Uppy also has hooks and more React examples in the React docs.

Install

npm install @uppy/core @uppy/dashboard @uppy/react

Tus

Tus is an open protocol for resumable uploads built on HTTP. This means accidentally closing your tab or losing connection lets you continue, for instance, your 10GB upload instead of starting all over.

Tus supports any language, any platform, and any network. It requires a client and server integration to work. We will be using tus Node.js.

Checkout the @uppy/tus docs for more information.

Create a route where you want to handle uploads:

import { useEffect, useState } from 'react';
import Uppy from '@uppy/core';
import Dashboard from '@uppy/react/lib/Dashboard';
import Tus from '@uppy/tus';

import '@uppy/core/dist/style.min.css';
import '@uppy/dashboard/dist/style.min.css';

function createUppy() {
return new Uppy().use(Tus, { endpoint: '/api/upload' });
}

export default function UppyDashboard() {
// Important: use an initializer function to prevent the state from recreating.
const [uppy] = useState(createUppy);

return <Dashboard theme="dark" uppy={uppy} />;
}

@tus/server does not support react router resource routes yet, which is based on the fetch Request API instead of http.IncomingMessage and http.ServerResponse.

However we can workaround it by using a custom server, which is a common pattern with React Router. The docs for this are still on the Remix site, but the same packages exist under the @react-router/* scope.

The exact code to integrate tus Node.js in your custom server depends on the framework you choose. Head over to the @tus/server examples for the most popular Node.js servers to find the one that works for you.

Transloadit

note

Before continuing you should have a Transloadit account and a template setup.

Transloadit’s strength is versatility. By doing video, audio, images, documents, and more, you only need one vendor for all your file processing needs. The @uppy/transloadit plugin directly uploads to Transloadit so you only have to worry about creating a template. It uses Tus under the hood so you don’t have to sacrifice reliable, resumable uploads for convenience.

When you go to production always make sure to set the signature. Not using Signature Authentication can be a security risk. Signature Authentication is a security measure that can prevent outsiders from tampering with your Assembly Instructions.

Generating a signature should be done on the server to avoid leaking secrets.

Start by creating a resource route to generate the signature and params:

import { data } from 'react-router';
import type { ActionFunction } from 'rea';
import crypto from 'crypto';

function utcDateString(ms: number): string {
return new Date(ms)
.toISOString()
.replace(/-/g, '/')
.replace(/T/, ' ')
.replace(/\.\d+Z$/, '+00:00');
}

export const action: ActionFunction = async ({ request }) => {
// expire 1 hour from now (this must be milliseconds)
const expires = utcDateString(Date.now() + 1 * 60 * 60 * 1000);
const authKey = process.env.TRANSLOADIT_KEY;
const authSecret = process.env.TRANSLOADIT_SECRET;
const templateId = process.env.TRANSLOADIT_TEMPLATE_ID;

if (!authKey || !authSecret || !templateId) {
throw data({ error: 'Missing Transloadit credentials' }, { status: 500 });
}

const body = await request.json();
const params = JSON.stringify({
auth: {
key: authKey,
expires,
},
template_id: templateId,
fields: {
// You can use this in your template.
customValue: body.customValue,
},
// your other params like notify_url, etc.
});

const signatureBytes = crypto
.createHmac('sha384', authSecret)
.update(Buffer.from(params, 'utf-8'));
// The final signature needs the hash name in front, so
// the hashing algorithm can be updated in a backwards-compatible
// way when old algorithms become insecure.
const signature = `sha384:${signatureBytes.digest('hex')}`;

return data({ expires, signature, params });
};

On the client we want to fetch the signature and params from the server. You may want to send values from React state along to your endpoint, for instance to add fields which you can use in your template as global variables.

// app/routes/upload-transloadit.tsx
import { Transloadit } from '@uppy/transloadit';

function createUppy() {
const uppy = new Uppy();
uppy.use(Transloadit, {
async assemblyOptions() {
// You can send meta data along for use in your template.
// https://transloadit.com/docs/topics/assembly-instructions/#form-fields-in-instructions
const { meta } = uppy.getState();
const body = JSON.stringify({ customValue: meta.customValue });
const res = await fetch('/transloadit-params', {
method: 'POST',
body,
});
return res.json();
},
});
return uppy;
}

function Component({ customValue }) {
// IMPORTANT: passing an initializer function to prevent the state from recreating.
const [uppy] = useState(createUppy);

useEffect(() => {
if (customValue) {
uppy.setOptions({ meta: { customValue } });
}
}, [uppy, customValue]);
}

HTTP uploads to your backend

If you want to handle uploads yourself, you can use @uppy/xhr-upload.

Create a resource route, such as app/routes/upload/route.ts:

import { LocalFileStorage } from '@mjackson/file-storage/local';
import { type FileUpload, parseFormData } from '@mjackson/form-data-parser';
import { type ActionFunctionArgs } from 'react-router';

const fileStorage = new LocalFileStorage('./uploads');

export async function action({ request }: ActionFunctionArgs) {
const user = requireUser(request); // your optional logic
const uploadHandler = async (fileUpload: FileUpload) => {
const storageKey = `user-${user.id}-avatar`;
await fileStorage.set(storageKey, fileUpload);
return fileStorage.get(storageKey);
};
const formData = await parseFormData(request, uploadHandler);
for (const [key, value] of formData.entries()) {
console.log(key, value);
}
return Response.json(null);
}

Create a page with your Uppy instance:

import Uppy from '@uppy/core';
import Dashboard from '@uppy/react/lib/Dashboard';
import Xhr from '@uppy/xhr-upload';
import { useState } from 'react';

import '@uppy/core/dist/style.min.css';
import '@uppy/dashboard/dist/style.min.css';

function createUppy() {
return new Uppy().use(Xhr, { endpoint: '/upload' });
}

export default function UppyDashboard() {
// Important: use an initializer function to prevent the state from recreating.
const [uppy] = useState(createUppy);

return <Dashboard uppy={uppy} />;
}

If you want to send along other form fields with your upload, you can use @uppy/form.

import Uppy from '@uppy/core';
import Dashboard from '@uppy/react/lib/Dashboard';
import Xhr from '@uppy/xhr-upload';
import Form from '@uppy/form';
import { useEffect, useState } from 'react';

import '@uppy/core/dist/style.min.css';
import '@uppy/dashboard/dist/style.min.css';

function createUppy() {
return new Uppy().use(Xhr, { endpoint: '/upload' });
}

export default function UppyDashboard() {
// Important: use an initializer function to prevent the state from recreating.
const [uppy] = useState(createUppy);

// @uppy/form is client-side only so we need to install it
// when the component is mounted.
useEffect(() => {
uppy.use(Form, { target: '#form' });
return () => uppy.removePlugin(uppy.getPlugin('Form')!);
}, [uppy]);

return (
<form id="form">
<label htmlFor="dob">Date of birth: </label>
<input type="date" name="dob" />
<Dashboard uppy={uppy} />;
</form>
);
}

Next steps

  • Add client-side file restrictions.
  • Upload files together with other form fields with @uppy/form.
  • Use your language of choice instead of English.
  • Add an image editor for cropping and resizing images.
  • Download files from remote sources, such as Google Drive and Dropbox, with Companion.
  • Add Golden Retriever to save selected files in your browser cache, so that if the browser crashes, or the user accidentally closes the tab, Uppy can restore everything and continue uploading as if nothing happened.