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 tostorage.getItem
orstorage.getKeys
when path ending with/
or/:
HEAD
: Maps tostorage.hasItem
. Returns 404 if not found.PUT
: Maps tostorage.setItem
. Value is read from body and returnsOK
if operation succeeded.DELETE
: Maps tostorage.removeItem
orstorage.clear
when path ending with/
or/:
. ReturnsOK
if operation succeeded.
When passing
accept: application/octet-stream
for GET and SET operations, the server switches to binary mode via getItemRaw
and setItemRaw
.