Guide
HTTP Server
We can expose unstorage's instance to an HTTP server to allow remote connections.
Request url is mapped to a key and method/body is mapped to a 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. Check out also listhen for an elegant HTTP listener.
🛡️ Security Note: Make sure to always implement
authorize
in order to protect the 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 the path ends with/
or/:
HEAD
: Maps tostorage.hasItem
. Returns 404 if not found.PUT
: Maps tostorage.setItem
. Value is read from the body and returnsOK
if the operation succeeded.DELETE
: Maps tostorage.removeItem
orstorage.clear
when the path ends with/
or/:
. ReturnsOK
if the operation succeeded.
When passing
accept: application/octet-stream
for GET and SET operations, the server switches to binary mode via getItemRaw
and setItemRaw
.