Utils

Advanced

More utilities

Session utils

clearSession(event, config)

Clear the session data for the current request.

getSession(event, config)

Get the session for the current request.

sealSession(event, config)

Encrypt and sign the session data for the current request.

unsealSession(_event, config, sealed)

Decrypt and verify the session data for the current request.

updateSession(event, config, update?)

Update the session data for the current request.

useSession(event, config)

Create a session manager for the current request.

deleteCookie(event, name, serializeOptions?)

Remove a cookie by name.

getCookie(event, name)

Get a cookie value by name.

parseCookies(event)

Parse the request to get HTTP Cookie header string and returning an object of all cookie name-value pairs.

setCookie(event, name, value, options?)

Set a cookie value by name.

getRequestFingerprint(event, opts)

Get a unique fingerprint for the incoming request.

defineWebSocket(hooks)

Define WebSocket hooks.

defineWebSocketHandler(hooks)

Define WebSocket event handler.

sanitizeStatusCode(statusCode?, defaultStatusCode)

Make sure the status code is a valid HTTP status code.

sanitizeStatusMessage(statusMessage)

Make sure the status message is safe to use in a response.

Allowed characters: horizontal tabs, spaces or visible ascii characters: https://www.rfc-editor.org/rfc/rfc7230#section-3.1.2

withBase(base, input)

Returns a new event handler that removes the base url of the event before calling the original handler.

Example:

handleCacheHeaders(event, opts)

Check request caching headers (If-Modified-Since) and add caching headers (Last-Modified, Cache-Control) Note: public cache control will be added by default

fetchWithEvent(event, req, init?, options?: { fetch: F })

Make a fetch request with the event's context and headers.

getProxyRequestHeaders(event)

Get the request headers object without headers known to cause issues when proxying.

proxy(event, target, opts)

Make a proxy request to a target URL and send the response back to the client.

proxyRequest(event, target, opts)

Proxy the incoming request to a target URL.

appendCorsHeaders(event, options)

Append CORS headers to the response.

appendCorsPreflightHeaders(event, options)

Append CORS preflight headers to the response.

handleCors(event, options)

Handle CORS for the incoming request.

If the incoming request is a CORS preflight request, it will append the CORS preflight headers and send a 204 response.

If return value is true, the request is handled and no further action is needed.

Example:

isCorsOriginAllowed(origin, options)

Check if the incoming request is a CORS request.

isPreflightRequest(event)

Check if the incoming request is a CORS preflight request.

createEventStream(event, opts?)

Initialize an EventStream instance for creating server sent events

Example:

Fingerprint utils

WebSocket utils

Sanitize

Base

const api = createApp()
 .get("/", () => "Hello API!");
const app = createApp();
 .use("/api/**", withBase("/api", api.handler));

Cache

Proxy

CORS

const app = createApp();
const router = createRouter();
router.use("/", async (event) => {
 const corsRes = handleCors(event, {
    origin: "*",
    preflight: {
      statusCode: 204,
    },
    methods: "*",
  });
  if (corsRes) {
    return corsRes;
  }
  // Your code here
 });
);

Server Sent Events (SSE)

import { createEventStream, sendEventStream } from "h3";

app.use("/sse", (event) => {
  const eventStream = createEventStream(event);

  // Send a message every second
  const interval = setInterval(async () => {
    await eventStream.push("Hello world");
  }, 1000);

  // cleanup the interval and close the stream when the connection is terminated
  eventStream.onClosed(async () => {
    console.log("closing SSE...");
    clearInterval(interval);
    await eventStream.close();
  });

  return eventStream.send();
});