Back to H3

Advanced

docs/2.utils/98.advanced.md

1.15.114.7 KB
Original Source

Advanced

More utilities

Session utils

<!-- automd:jsdocs src="../../src/utils/session.ts" -->

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.

<!-- /automd --> <!-- automd:jsdocs src="../../src/utils/cookie.ts" -->

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 return an object of all cookie name-value pairs.

setCookie(event, name, value, serializeOptions)

Set a cookie value by name.

<!-- /automd -->

Sanitize

<!-- automd:jsdocs src="../../src/utils/sanitize.ts" -->

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

<!-- /automd -->

Route

<!-- automd:jsdocs src="../../src/utils/route.ts" -->

useBase(base, handler)

Prefixes and executes a handler with a base path.

Example:

ts
const app = createApp();
const router = createRouter();
const apiRouter = createRouter().get(
  "/hello",
  defineEventHandler((event) => {
    return "Hello API!";
  }),
);
router.use("/api/**", useBase("/api", apiRouter.handler));
app.use(router.handler);
<!-- /automd -->

Cache

<!-- automd:jsdocs src="../../src/utils/cache.ts" -->

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

<!-- /automd -->

Proxy

<!-- automd:jsdocs src="../../src/utils/proxy.ts" -->

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

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

getProxyRequestHeaders(event, opts?: { host? })

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

proxyRequest(event, target, opts)

Proxy the incoming request to a target URL.

sendProxy(event, target, opts)

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

<!-- /automd -->

CORS

<!-- automd:jsdocs src="../../src/utils/cors/index.ts" -->

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:

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

isCorsOriginAllowed(origin, options)

Check if the incoming request is a CORS request.

isPreflightRequest(event)

Check if the incoming request is a CORS preflight request.

<!-- /automd -->

Server Sent Events (SSE)

<!-- automd:jsdocs src="../../src/utils/sse/index.ts" -->

createEventStream(event, opts?)

Initialize an EventStream instance for creating server sent events

Example:

ts
import { createEventStream, sendEventStream } from "h3";

eventHandler((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();
});
<!-- /automd -->