Guide

HTTP Server

We can expose unstorage instance to an http server to allow remote connections.


Request url is mapped to key and method/body mapped to function. See below for supported http methods.

Storage Server

Programmatic usage of creating an HTTP server exposing methods to communicate with the storage instance:

server.js
import { listen } from "listhen";
import { createStorage } from "unstorage";
import { createStorageServer } from "unstorage/server";

const storage = createStorage();
const storageServer = createStorageServer(storage, {
  authorize(req) {
    // req: { key, type, event }
    if (req.type === "read" && req.key.startsWith("private:")) {
      throw new Error("Unauthorized Read");
    }
  },
});

// Alternatively we can use `storageServer.handle` as a middleware
await listen(storageServer.handle);

The storageServer is an h3 instance. Checkout also listhen for an elegant HTTP listener.

🛡️ Security Note: Make sure to always implement authorize in order to protect server when it is exposed to a production environment.

Storage Client

You can use the http driver to easily connect to the server.

import { createStorage } from "unstorage";
import httpDriver from "unstorage/drivers/http";

const client = createStorage({
  driver: httpDriver({
    base: "SERVER_ENDPOINT",
  }),
});
const keys = await client.getKeys();

HTTP Methods

  • GET: Maps to storage.getItem or storage.getKeys when path ending with / or /:
  • HEAD: Maps to storage.hasItem. Returns 404 if not found.
  • PUT: Maps to storage.setItem. Value is read from body and returns OK if operation succeeded.
  • DELETE: Maps to storage.removeItem or storage.clear when path ending with / or /:. Returns OK if operation succeeded.
When passing accept: application/octet-stream for GET and SET operations, the server switches to binary mode via getItemRaw and setItemRaw.