Download button (Next.js)

This example demonstrates how to create a download button in a Next.js application using tokens.

On the server side (pages router)

pages/api/token.ts
import { f0 } from "file0";
export default async function handler(req, res) {
  // Authorize the user here...
  const token = await f0.createToken("example.json", {
    expiresIn: '1h',
    maxUploadSize: '1mb'
  });
  res.json({ token });
}

On the client side

DownloadButton.tsx
import { f0 } from "file0";
export function DownloadButton() {
  const download = async () => {
    const { token } = await fetch("/api/token")
      .then((res) => res.json());
    const blob = f0.useToken(token).get({ as: "blob" });
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "example.json";
    a.target = "_blank";
    a.click();
    URL.revokeObjectURL(downloadUrl);
  };
  return (
    <button onClick={download}>Download</button>
  );
}

Last updated