KScript docs
EN

Routes and APIs

Middleware

Writing middleware

Middleware is a function that takes the request and a next function. Return a response to stop the request, or call $next($request) to carry on, and change the response it gives back if you like:

<!-- middleware/security.kscript -->
<kscript>
  <import package="KScript.Http" />

  <fn name="secure_headers" params="request: map, next: fn">
    <return value="$next($request)->with_header('X-Frame-Options', 'DENY')" />
  </fn>

  <fn name="json_only" params="request: map, next: fn">
    <if $request.method == 'POST' and not ($request.headers['content-type'] ?? '')->contains('json')>
      <return value="@response({ error: 'Send JSON.' }, status: 415)" />
    </if>
    <return value="$next($request)" />
  </fn>
</kscript>
// middleware/security.kscript
kscript {
  import KScript.Http

  fn secure_headers(request: map, next: fn) {
    return $next($request)->with_header('X-Frame-Options', 'DENY')
  }

  fn json_only(request: map, next: fn) {
    if $request.method == 'POST' and not ($request.headers['content-type'] ?? '')->contains('json') {
      return @response({ error: 'Send JSON.' }, status: 415)
    }
    return $next($request)
  }
}

The two parameters are positional. They may be untyped, and more parameters may follow if they have defaults. KScript checks the signature when it loads the route, and the editor checks every reference to the function.

Using middleware

Middleware applies at four levels, and the outermost runs first:

  1. http.middleware in kscript.json, for every route.
  2. Routes(middleware: …), for every route in the file. Middleware(use: …) adds more for the routes after it.
  3. Group(middleware: …), for the routes inside the group.
  4. Get(…, middleware: …), for one route.
<!-- routes.kscript -->
<KScript.Routes>
  <import path="middleware/security.kscript" />

  <Middleware use="secure_headers, json_only" />
</KScript.Routes>
// routes.kscript
import KScript.Http
import "middleware/security.kscript"

Routes {
  Middleware(use: [secure_headers, json_only])
}

A middleware list is an array of names, such as [log, secure_headers, throttle:30]. Each name is a built-in, a function (one from an imported script too), or a group name from http.groups. A built-in takes its argument after a colon, as in throttle:30. A single name needs no brackets: middleware: auth.

In XML, attributes are text, so the same list is written use="secure_headers, json_only". In .kscript files, a list written as one string (use: "log, cors") is an error (KS6006), and kscript check --fix rewrites it as an array. The same goes for every list of names: only, except, methods and <llm tools>.

Built-in middleware

Name What it does
log Writes each request to the server log: what answered it, the route name, the status and the time.
cors Answers browser preflight requests and adds Access-Control-Allow-Origin. The allowed origins, methods, headers and credentials come from http.cors.
auth Lets through someone signed in with KScript.Auth, by the session cookie or an API token, and sets $request.user. It also accepts Authorization: Bearer <token> matching the API_TOKEN environment variable (http.auth.token_env names another). Anyone else is sent to http.auth.login (/login) in a browser, or gets 401 when they want JSON. auth:session and auth:token accept only one kind of sign-in. auth:ADMIN_TOKEN accepts only the token in that variable, and refuses every request (500) when it isn't set. Requests that pass have $request.authenticated set.
guest Lets through only people who aren't signed in, for the sign-in and sign-up pages. Others are sent to http.auth.home (/), or get 403 when they want JSON.
signed Lets through only URLs made by @signed_url() that haven't been changed or run out. Others get 403.
verified Lets through only signed-in users who have verified their email with @verify_email(). Guests are treated as auth treats them. Others are sent to the route named verification.notice in a browser, or get 403.
csrf Needs the session's CSRF token on every request except GET, HEAD and OPTIONS, as a _token form field or an X-CSRF-Token header. Without it, 419 Page Expired. Web routes in a file that imports KScript.Auth get it on their own (see Forms and CSRF).
throttle Allows 60 requests a minute per client address and route (http.throttle), or the number you give: throttle:30. throttle:user (or throttle:30:user) counts a signed-in user's requests wherever they come from, and visitors by address. Over the limit gets 429 with Retry-After. Every response has X-RateLimit-Limit and X-RateLimit-Remaining.
etag Tags GET answers with an ETag, and answers If-None-Match with 304 Not Modified (see Caching and ETags). etag:weak gives weak tags.
cache_control Sets Cache-Control on GET answers: cache_control:300 (public for five minutes) or cache_control:private;max-age=60.
cache_response Keeps whole GET answers in memory and answers again from there: cache_response:5m (one minute if you don't say).

A function with the same name as a built-in wins, so you may replace one.