Class ServerConfig

java.lang.Object
io.karatelabs.http.ServerConfig

public class ServerConfig extends Object
Configuration for the HTTP server including routing, sessions, and security settings. Use the builder pattern for fluent configuration.
  • Constructor Details

    • ServerConfig

      public ServerConfig()
    • ServerConfig

      public ServerConfig(String resourceRoot)
  • Method Details

    • getResourceRoot

      public String getResourceRoot()
    • getContextPath

      public String getContextPath()
    • isDevMode

      public boolean isDevMode()
    • isDevTrace

      public boolean isDevTrace()
    • getSessionExpirySeconds

      public int getSessionExpirySeconds()
    • getSessionCookieName

      public String getSessionCookieName()
    • getSessionStore

      public SessionStore getSessionStore()
    • getApiPrefix

      public String getApiPrefix()
    • isApiPrefixEnabled

      public boolean isApiPrefixEnabled()
    • getStaticPrefix

      public String getStaticPrefix()
    • isStaticPrefixEnabled

      public boolean isStaticPrefixEnabled()
    • isCsrfEnabled

      public boolean isCsrfEnabled()
    • getSessionSameSite

      public SameSite getSessionSameSite()
    • isCsrfExemptPath

      public boolean isCsrfExemptPath(String path)
    • getAllowedOrigins

      public String[] getAllowedOrigins()
    • isSecurityHeadersEnabled

      public boolean isSecurityHeadersEnabled()
    • getContentSecurityPolicy

      public String getContentSecurityPolicy()
    • getXFrameOptions

      public String getXFrameOptions()
    • getReferrerPolicy

      public String getReferrerPolicy()
    • isHstsEnabled

      public boolean isHstsEnabled()
    • getHstsMaxAge

      public long getHstsMaxAge()
    • isHstsIncludeSubDomains

      public boolean isHstsIncludeSubDomains()
    • getErrorTemplate404

      public String getErrorTemplate404()
    • getErrorTemplate500

      public String getErrorTemplate500()
    • getTemplateRoutes

      public LinkedHashMap<String,String> getTemplateRoutes()
    • getShellTemplate

      public String getShellTemplate()
    • getRawPaths

      public Set<String> getRawPaths()
    • getRequestInterceptor

      public Consumer<HttpRequest> getRequestInterceptor()
    • getRequestFilter

    • getLogHandler

      public Consumer<String> getLogHandler()
    • getEngineSupplier

      public Supplier<io.karatelabs.js.Engine> getEngineSupplier()
    • getGlobalVariables

      public Map<String,Object> getGlobalVariables()
    • resourceRoot

      public ServerConfig resourceRoot(String resourceRoot)
    • contextPath

      public ServerConfig contextPath(String contextPath)
    • devMode

      public ServerConfig devMode(boolean devMode)
    • devTrace

      public ServerConfig devTrace(boolean devTrace)
      Enable fragment-trace HTML comments around every th:insert / th:replace resolution. Useful for debugging composition.

      Requires devMode(boolean) = true as a precondition — trace emission is silently a no-op outside dev mode (production safety: never leak fragment names or scope payloads to end users).

      Can also be enabled via the KARATE_DEV_TRACE=true environment variable, which is read once when ServerConfig is constructed. Programmatic configuration via this method overrides the env var.

    • sessionExpirySeconds

      public ServerConfig sessionExpirySeconds(int sessionExpirySeconds)
    • sessionCookieName

      public ServerConfig sessionCookieName(String sessionCookieName)
    • sessionStore

      public ServerConfig sessionStore(SessionStore sessionStore)
    • apiPrefix

      public ServerConfig apiPrefix(String apiPrefix)
    • apiPrefixEnabled

      public ServerConfig apiPrefixEnabled(boolean apiPrefixEnabled)
    • staticPrefix

      public ServerConfig staticPrefix(String staticPrefix)
    • staticPrefixEnabled

      public ServerConfig staticPrefixEnabled(boolean staticPrefixEnabled)
    • csrfEnabled

      public ServerConfig csrfEnabled(boolean csrfEnabled)
    • csrfExemptPaths

      public ServerConfig csrfExemptPaths(String... csrfExemptPaths)
      Register paths where CSRF token validation is skipped. Use for endpoints that legitimately receive cross-site POSTs without a CSRF token but have their own anti-CSRF mechanism, for example:
      • OAuth/OIDC response_mode=form_post callbacks — the IdP posts code+state back to /signin; the state parameter validation provides CSRF protection.
      • Webhook receivers where authenticity is verified via a signature header (e.g. Stripe, GitHub).

      Exact path match (not prefix). For more granular control, use requestFilter(java.util.function.BiFunction).

    • sessionSameSite

      public ServerConfig sessionSameSite(SameSite sessionSameSite)
      Set the SameSite attribute on the session cookie. Default is SameSite.LAX, which works for ordinary form posts and OAuth callbacks that use response_mode=query.

      Switch to SameSite.NONE when an OAuth/OIDC provider uses response_mode=form_post (cross-site top-level POST back to your callback URL). Lax cookies are dropped on cross-site POSTs by every standards-compliant browser, so the session cookie set during the pre-redirect signin flow would not survive the IdP's POST back. None requires Secure, which is added automatically outside dev mode.

      When using None, ensure the path receiving the cross-site POST is in csrfExemptPaths(String...) (the IdP cannot send your CSRF token) and that the path performs its own CSRF check (OAuth state parameter validation).

    • allowedOrigins

      public ServerConfig allowedOrigins(String... allowedOrigins)
    • securityHeadersEnabled

      public ServerConfig securityHeadersEnabled(boolean securityHeadersEnabled)
    • contentSecurityPolicy

      public ServerConfig contentSecurityPolicy(String contentSecurityPolicy)
    • xFrameOptions

      public ServerConfig xFrameOptions(String xFrameOptions)
    • referrerPolicy

      public ServerConfig referrerPolicy(String referrerPolicy)
    • hstsEnabled

      public ServerConfig hstsEnabled(boolean hstsEnabled)
    • hstsMaxAge

      public ServerConfig hstsMaxAge(long hstsMaxAge)
    • hstsIncludeSubDomains

      public ServerConfig hstsIncludeSubDomains(boolean hstsIncludeSubDomains)
    • errorTemplate404

      public ServerConfig errorTemplate404(String errorTemplate404)
    • errorTemplate500

      public ServerConfig errorTemplate500(String errorTemplate500)
    • templateRoute

      public ServerConfig templateRoute(String pathPattern, String templateName)
      Add a path pattern → template mapping. Checked before file resolution — routes take priority. The original request path is preserved so the template can use request.pathMatches() to extract parameters.

      Example:

       config.templateRoute("/sessions/{id}", "session.html")
             .templateRoute("/sessions/{id}/report", "report.html")
             .templateRoute("/flows/{path}", "flows.html")
       

      Register more specific patterns first.

    • shellTemplate

      public ServerConfig shellTemplate(String shellTemplate)
      Set a layout shell template that wraps full-page navigations. The shell's th:utext="content" slot receives the rendered content template's HTML.

      The wrap is skipped when:

      • The request has the HX-Request header (HTMX fragment swap)
      • The resolved path is in rawPaths(String...)
      • The resolved template equals the shell template (defensive anti-recursion)
      • The resolved content short-circuited with context.redirect()

      Content renders first (so its ka:scope side effects — flash, session, switch, redirect — commit before the shell evaluates). If content calls context.switch(t), the switched template becomes the new content and the shell still wraps it.

      The shell receives these additional template variables:

      • content — the rendered content HTML (use th:utext="content")
      • contentTemplate — the resolved content template path (e.g., items.html)
    • rawPaths

      public ServerConfig rawPaths(String... rawPaths)
      Register paths that ship their own full HTML shell and should NOT be wrapped with shellTemplate(String). Typical uses: /signin, /signout, landing pages with bespoke branding.

      Exact path match (not prefix). Use the request path, not the template name.

    • requestInterceptor

      public ServerConfig requestInterceptor(Consumer<HttpRequest> requestInterceptor)
    • requestFilter

      public ServerConfig requestFilter(BiFunction<HttpRequest,ServerMarkupContext,HttpResponse> requestFilter)
      Set a request filter that runs after session loading but before CSRF validation. The filter receives the request and fully initialized context (with session loaded). Return null to continue normal processing, or an HttpResponse to short-circuit.

      Use this to:

      • Set context.setSession(Session.TEMPORARY) for public API endpoints (webhooks)
      • Return a 401/403 response for unauthorized requests based on session state
      • Implement centralized auth validation across all routes
    • logHandler

      public ServerConfig logHandler(Consumer<String> logHandler)
    • engineSupplier

      public ServerConfig engineSupplier(Supplier<io.karatelabs.js.Engine> engineSupplier)
      Set a custom ExternalBridge to control Java interop. Override forType() to restrict which Java classes can be accessed from templates. By default, all classes are accessible.
    • globalVariables

      public ServerConfig globalVariables(Map<String,Object> globalVariables)
      Set global variables that will be available in all templates and API handlers. These variables are injected into the JavaScript engine context.
    • isApiPath

      public boolean isApiPath(String path)
      Check if the given path should be handled as an API route.
    • isStaticPath

      public boolean isStaticPath(String path)
      Check if the given path should be served as a static file.
    • isRawPath

      public boolean isRawPath(String path)
      Check if the given request path opts out of shell-wrap.
    • isSessionEnabled

      public boolean isSessionEnabled()
      Check if sessions are enabled.
    • createSession

      public Session createSession()
      Create a new session using the configured session store. Returns null if sessions are not enabled.
    • toString

      public String toString()
      Overrides:
      toString in class Object