The Kubernetes Gateway API provides a standardized way to configure L7 routing in Kubernetes. Through resources like HTTPRoute, you get path matching, header rewrites, URL redirects, and traffic splitting, which cater for majority of use cases. Where it falls short is when you need to do more advanced capabilities or custom logic such as:
- Inspecting or modifying request/response bodies
- Making sideband calls to external APIs mid-request (e.g. auth checks, content scanning)
- Conditional routing based on body content
These are possible on vanilla NGINX through NJS (NGINX JavaScript), but there are some hurdles with wiring NJS into F5 NGINX Gateway Fabric - while NGINX Gateway Fabric uses NGINX for the data plane, the NGINX configuration is generated from Kubernetes resources rather than managed directly.
In this post, I’ll go through a pattern for injecting NJS logic into NGINX Gateway Fabric using its extension points, what each Kubernetes resource maps to in the generated NGINX config, and how I applied it to build an F5 AI Guardrails integration with NGINX Gateway Fabric to deliver and secure LLM-powered application.
Table of Contents
- Overview on Request Interception with NJS
- Translating to NGINX Gateway Fabric
- Resulting NGINX Gateway Fabric Configuration
- Example - F5 AI Guardrails integration
- Summary
Overview on Request Interception with NJS
In a typical NGINX setup, a request arrives at a location block with a proxy_pass directive, gets forwarded to the backend, and the response goes straight back to the client. There’s no hook point between the upstream response and the client.
NJS changes this with the following directive/function:
- js_content replaces proxy_pass for a location. Instead of proxying, the request is handed to a JavaScript function
- r.subrequest() from inside that function, makes an internal request to another NGINX location, effectively forwarding the request to the backend and returning the response to the NJS function
This gives us a two-location pattern:
- A client-facing location (e.g. /app/) with js_content - this is where the NJS function intercepts the request
- An internal location (e.g. /_backend/) with proxy_pass - this is the subrequest target that actually proxies to the backend
# Client-facing location - intercepts requests with NJS
location /app/ {
js_content main.handleRequest;
}
# Internal location - only reachable via r.subrequest()
location /_backend/ {
internal;
proxy_pass http://backend:8000/;
}
supplemented by an NJS script as such:
async function handleRequest() {
// request manipulation
...
// proxy request to backend
response = await r.subrequest('/_backend/app/');
...
// response manipulation
...
// respond back to client
r.headersOut['test'] = 'hello world';
r.return(resp_code, resp_body);
}
which makes both request and response manipulation possible from a single handler. The traffic flow then becomes:
- Client sends request to /app/, which hits the js_content location
- NJS function runs - validates the body, calls an external service, modifies headers, etc.
- NJS calls r.subrequest(‘/_backend/app/’) to forward to the backend via the internal
/_backend/ location - The upstream response comes back to the NJS function in the /app/ location
- NJS inspects/modifies the response, then calls r.return() to send the final response to the client
You can see some examples here.
Translating to NGINX Gateway Fabric
NGINX Gateway Fabric uses NGINX as its data plane, but the NGINX configuration is generated from Kubernetes resources - there’s no nginx.conf to edit directly. To illustrate, a basic HTTPRoute like:
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: backend
spec:
parentRefs:
- name: gateway
sectionName: http
hostnames:
- "backend.example.com"
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: backend
port: 8000
generates an NGINX config that looks roughly like:
server {
server_name backend.example.com;
location / {
proxy_pass http://backend:8000;
}
}
To inject NJS logic, we need to work with NGINX Gateway Fabric’s extension points to manipulate the generated NGINX config. There are four things that need to happen:
- Get the NJS scripts onto the NGINX container’s filesystem
- Load the scripts with js_import at the http context
- Create the js_content handler location
- Rewire the HTTPRoute to serve the internal /_backend/ location
Let’s go through each one.
Prerequisite: The pattern below relies on Snippets which need to be enabled on your NGINX Gateway Fabric deployment.
1. Mounting NJS Scripts - NginxProxy
NJS scripts need to be on disk for NGINX to load them. The scripts are stored in a ConfigMap:
apiVersion: v1
kind: ConfigMap
metadata:
name: my-njs-configmap
data:
main.js: |
async function handleRequest(r) {
// request manipulation
...
// proxy request to backend via internal location
let resp = await r.subrequest('/_backend/app/');
// response manipulation
...
r.return(resp.status, resp.responseText);
}
export default { handleRequest };
Since NGINX Gateway Fabric manages the NGINX container, we can’t bake files into the image. Instead, the NginxProxy resource lets us add volume mounts to the NGINX Gateway Fabric deployment:
apiVersion: gateway.nginx.org/v1alpha2
kind: NginxProxy
metadata:
name: my-proxy
spec:
kubernetes:
deployment:
container:
volumeMounts:
- name: njs-scripts
mountPath: /etc/nginx/modules/njs/scripts
readOnly: true
pod:
volumes:
- name: njs-scripts
configMap:
name: my-njs-configmap
This mounts a ConfigMap containing the .js files into the NGINX container. Secrets can be mounted the same way - useful for API keys or other sensitive config that NJS reads at runtime via the File System module.
The Gateway resource then references the NginxProxy:
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: gateway
spec:
gatewayClassName: nginx
infrastructure:
parametersRef:
name: my-proxy
group: gateway.nginx.org
kind: NginxProxy
listeners:
- name: http
port: 8000
protocol: HTTP
2. Loading the Module - SnippetsPolicy
With the files on disk, NGINX needs a js_import directive in the http context to load them. SnippetsPolicy handles this:
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsPolicy
metadata:
name: njs-setup
spec:
targetRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: gateway
snippets:
- context: http
value: |
js_import main from modules/njs/scripts/main.js;
This is also where you’d put supporting directives, e.g. js_fetch_trusted_certificate if the NJS code makes outbound HTTPS calls.
3. Creating the Handler - SnippetsFilter
The SnippetsFilter does two things in one resource:
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsFilter
metadata:
name: my-handler
spec:
snippets:
- context: http.server.location
value: |
internal;
- context: http.server
value: |
location /app/ {
js_content main.handleRequest;
}
The http.server snippet creates the client-facing location /app/ block with js_content - the entry point for incoming requests.
The http.server.location snippet injects internal; into the location block that the HTTPRoute generates (next step). This makes the /_backend/ location unreachable from outside - only r.subrequest() can access it.
4. Rewiring the HTTPRoute
In a standard setup, the HTTPRoute matches the client-facing path and proxies to the backend:
# Before - standard routing
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: backend
port: 8000
With NJS in the picture, the HTTPRoute’s job changes. It now defines the /_backend/ internal location - the subrequest target. The client-facing path is handled by the js_content location from step 3.
# After - NJS-mediated routing
rules:
- matches:
- path:
type: PathPrefix
value: /_backend/
filters:
- type: URLRewrite
urlRewrite:
path:
type: ReplacePrefixMatch
replacePrefixMatch: /
- type: ExtensionRef
extensionRef:
group: gateway.nginx.org
kind: SnippetsFilter
name: my-handler
backendRefs:
- name: backend
port: 8000
The URLRewrite filter strips the /_backend/ prefix so requests arrive at the backend with the original path. The ExtensionRef attaches the SnippetsFilter, which marks the generated location as internal and injects the js_content handler for the client-facing path.
Resulting NGINX Gateway Fabric Configuration
Putting it all together, here’s what the generated NGINX config looks like (simplified):
http {
js_import main from modules/njs/scripts/app.js; # SnippetsPolicy
server {
# Client-facing - injected by SnippetsFilter
location /app/ {
js_content main.handleRequest;
}
# Internal backend - generated from HTTPRoute + SnippetsFilter
location /_backend/ {
internal; # SnippetsFilter
rewrite ^/_backend/(.*)$ /$1 break; # HTTPRoute URLRewrite
proxy_pass http://backend:8000; # HTTPRoute backendRefs
}
}
}
Example - F5 AI Guardrails integration
I put together a reference implementation using this pattern to integrate F5 AI Guardrails with NGINX Gateway Fabric on GitHub: f5-ai-guardrails-with-nginx-gateway-fabric.
The NJS handler intercepts OpenAI Chat Completions API requests and scans both prompts and LLM responses through the F5 AI Guardrails API. If content gets flagged, the handler blocks or redacts it before it reaches the client. It handles both streaming (SSE) and non-streaming responses.
The repo has the full manifests, a test script, and worked examples for each flow. Have a look if you want to see the pieces working together in practice.
Summary
Hopefully this post has helped shed some light on how the NGINX Gateway Fabric data plane can be re-programmed via NJS with Kubernetes resources. The two-layer pattern (js_content + internal backend route) is the trick that makes it work cleanly. It’s some extra moving parts, but it unlocks use cases the Gateway API doesn’t handle well today.

