Day 4: Plugins
Goal: Use plugins globally, on the service and on the route, understand precedence and order, and solve typical tasks with CORS, cache and maintenance mode. · Duration: approx. 60 min · Prerequisite: Day 3
Briefing
- A plugin hooks into the processing of a request. It applies globally, to a service, a route or a consumer (Day 5).
- If the same plugin exists on several levels, only the most specific one runs: route before service before global.
- Different plugins run according to their fixed priority, not according to the order in the file.
- You add plugins with
deck file add-plugins; the plugin files are in the companion code.
Request ─► correlation-id (100001) ─► cors (2000) ─► … ─► proxy-cache (100)
global Service notes Route notes-lesen
─► request-termination (2) ─► Backend
Drill 1: Global Plugins
source ~/kong-lab/setup/env.sh
mkdir -p ~/kong-lab/tag04 && cd ~/kong-lab/tag04
cp ~/kong-lab/code/tag04/*.yaml .
cat global.yaml
deck file add-plugins -s ~/kong-lab/kong/kong.yaml global.yaml -o neu.yaml
deck gateway diff neu.yaml | grep -E '^creating|Created'
cp neu.yaml ~/kong-lab/kong/kong.yaml && kreload
curl -s $PROXY/echo/headers | jq -c '.headers | {"X-Ebene", "X-Correlation-Id"}'
curl -si $PROXY/api/v1/version | grep -i correlationExpected (shortened, your IDs will differ):
# global.yaml – Plugins für alle Anfragen (Tag 4)
_format_version: "1.0"
add-plugins:
- plugins:
- name: correlation-id
…
creating plugin correlation-id (global)
creating plugin request-transformer (global)
Created: 2
Kong reloaded
{"X-Ebene":["global"],"X-Correlation-Id":["a6f247e0-…"]}
X-Correlation-ID: 9aa3ef58-…
Without selectors, the plugins end up in the top-level
plugins: list and apply to every request.
correlation-id gives every request an ID that both the
backend and the client see
(echo_downstream).
Save your progress? Sign up for free
Drill 2: The Most Specific Plugin Wins
echo.yaml sets request-transformer once
more, this time only on the echo service:
grep -A12 selectors echo.yaml
deck file add-plugins -s ~/kong-lab/kong/kong.yaml echo.yaml -o neu.yaml
cp neu.yaml ~/kong-lab/kong/kong.yaml && kreload
curl -s $PROXY/echo/headers | jq -c '.headers | {"X-Ebene", "User-Agent"}'
curl -s -X DELETE $PROXY/api/x | jq -c '.headers | {"X-Ebene", "User-Agent"}'Expected:
- selectors:
- $.services[?(@.name=="echo")]
plugins:
- name: request-transformer
config:
add:
headers: ["X-Ebene:service"]
remove:
headers: ["User-Agent"]
Kong reloaded
{"X-Ebene":["service"],"User-Agent":null}
{"X-Ebene":["global"],"User-Agent":["curl/8.5.0"]}
For the echo service, only the service variant runs:
X-Ebene: service, no User-Agent. The catch-all
route /api belongs to a different service and still gets
the global one. The two configurations are not
merged.
Save your progress? Sign up for free
Drill 3: The Order
curl -s $ADMIN | jq -r '.plugins.available_on_server | to_entries
| map(select(.key | IN("correlation-id","cors","jwt","key-auth","acl",
"rate-limiting","request-transformer","proxy-cache","request-termination")))
| sort_by(-.value.priority) | .[] | "\(.value.priority)\t\(.key)"'Expected:
100001 correlation-id
2000 cors
1450 jwt
1250 key-auth
950 acl
910 rate-limiting
801 request-transformer
100 proxy-cache
2 request-termination
Higher priority runs first. That is why Kong first checks
who is asking (jwt,
key-auth), then whether they are allowed
(acl), then how often
(rate-limiting). cors comes before them so
that the browser can send its preflight request without a key.
Save your progress? Sign up for free
Drill 4: CORS and the Preflight Request
A web UI on http://localhost:3000 should be allowed to
call the API from the browser:
deck file add-plugins -s ~/kong-lab/kong/kong.yaml cors.yaml -o neu.yaml
cp neu.yaml ~/kong-lab/kong/kong.yaml && kreload
curl -si -X OPTIONS -H 'Origin: http://localhost:3000' \
-H 'Access-Control-Request-Method: POST' $PROXY/api/v1/notes \
| grep -i -E '^(HTTP|access-control)'Expected (shortened):
Kong reloaded
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, HEAD, PUT, DELETE, PATCH, QUERY, OPTIONS
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Max-Age: 3600
Looks good, but is wrong: these are not your values
(max_age 600, only GET and POST). The browser’s preflight
request is an OPTIONS, and OPTIONS matches no
notes route. It falls through to the catch-all route /api,
and the echo service answers with CORS headers of its own. The
notes-lesen route has to accept OPTIONS:
deck file patch -s ~/kong-lab/kong/kong.yaml \
--selector '$..routes[?(@.name=="notes-lesen")]' \
--value 'methods:["GET","OPTIONS"]' -o neu.yaml
cp neu.yaml ~/kong-lab/kong/kong.yaml && kreload
curl -si -X OPTIONS -H 'Origin: http://localhost:3000' \
-H 'Access-Control-Request-Method: POST' $PROXY/api/v1/notes \
| grep -i -E '^(HTTP|access-control)'Expected:
Kong reloaded
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Headers: Content-Type,X-API-Key
Access-Control-Allow-Methods: GET,POST
Access-Control-Max-Age: 600
Now the cors plugin answers itself, without asking the
backend.
Warning: Even an
Origin: http://boese.examplegetsAccess-Control-Allow-Origin: http://localhost:3000back. That is correct: the browser compares and blocks. CORS protects users in the browser, not the API fromcurl.
Save your progress? Sign up for free
Drill 5: A Cache in Front of the API
deck file add-plugins -s ~/kong-lab/kong/kong.yaml cache.yaml -o neu.yaml
cp neu.yaml ~/kong-lab/kong/kong.yaml && kreload
for i in 1 2 3; do
curl -si $PROXY/api/v1/notes \
| grep -i -E '^(x-cache-status|x-kong-upstream-latency)' | tr -d '\r' | tr '\n' ' '
echo
doneExpected:
Kong reloaded
X-Cache-Status: Miss X-Kong-Upstream-Latency: 9
X-Cache-Status: Hit X-Kong-Upstream-Latency: 0
X-Cache-Status: Hit X-Kong-Upstream-Latency: 0
The first call goes to the backend; for the next 30 seconds Kong answers from memory. The price: stale data.
curl -s $PROXY/api/v1/notes | jq length
curl -s -X POST -H 'X-API-Key: lab-api-key-123' -H 'Content-Type: application/json' \
-d '{"text":"neu im Cache?"}' $PROXY/api/v1/notes > /dev/null
curl -s $PROXY/api/v1/notes | jq length
curl -s -H 'Cache-Control: no-cache' $PROXY/api/v1/notes | jq length
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE $ADMIN/proxy-cache
curl -s $PROXY/api/v1/notes | jq lengthExpected:
2
2
2
204
3
The new note is missing until the entry expires or you purge the
cache through the Admin API. Even Cache-Control: no-cache
from the client does not help: the plugin ignores it as long as
cache_control: false is set (the default).
Save your progress? Sign up for free
Drill 6: Maintenance Mode
wartung.yaml puts a request-termination on
the notes-schreiben route, but with
enabled: false. Switching it on means changing one
field.
deck file add-plugins -s ~/kong-lab/kong/kong.yaml wartung.yaml -o neu.yaml
SEL='$..routes[?(@.name=="notes-schreiben")].plugins[?(@.name=="request-termination")]'
deck file patch -s neu.yaml --selector "$SEL" --value 'enabled:true' -o an.yaml
cp an.yaml ~/kong-lab/kong/kong.yaml && kreload
curl -si -X POST -H 'X-API-Key: lab-api-key-123' -H 'Content-Type: application/json' \
-d '{"text":"jetzt?"}' $PROXY/api/v1/notes | sed -n '1p;$p'; echo
curl -s -o /dev/null -w '%{http_code}\n' $PROXY/api/v1/notesExpected:
Kong reloaded
HTTP/1.1 503 Service Temporarily Unavailable
{"message":"Wartung bis 18 Uhr"}
200
Writing is blocked, reading still works.
request-termination has priority 2 and runs last:
authentication and rate limits still apply in maintenance mode.
Save your progress? Sign up for free
Drill 7: Final State
For the coming days, only correlation-id and
cors stay, along with the route for OPTIONS.
The companion code provides the state:
cp ~/kong-lab/code/tag04/kong.yaml ~/kong-lab/kong/kong.yaml
cd ~/kong-lab/kong && kreload
curl -s $ADMIN/plugins | jq -r '.data[] | [.name, (if .route then "route"
elif .service then "service" else "global" end)] | @tsv' | sort
git add kong.yaml && git commit -qm "Tag 4: correlation-id und cors"Expected:
Kong reloaded
correlation-id global
cors service
Save your progress? Sign up for free
Checkpoint
curl -si $PROXY/api/v1/notes | grep -i -c '^x-correlation-id'Expected: every response carries a correlation ID.
1
curl -si -X OPTIONS -H 'Origin: http://localhost:3000' \
-H 'Access-Control-Request-Method: POST' $PROXY/api/v1/notes \
| grep -i '^access-control-max-age'Expected: the plugin answers the preflight request with your
max_age.
Access-Control-Max-Age: 600
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'X-API-Key: lab-api-key-123' \
-H 'Content-Type: application/json' -d '{"text":"Tag 4"}' $PROXY/api/v1/notesExpected: no more maintenance mode, writing works.
201
Challenge
All responses that come in via the host echo.lab should
carry the header X-Lab: Trainingslager. Responses via
/echo should not.
Note: response-transformer on the right
route; --config takes the plugin as JSON.
Solution
cd ~/kong-lab/tag04
deck file add-plugins -s ~/kong-lab/kong/kong.yaml \
--selector '$..routes[?(@.name=="echo-host")]' \
--config '{"name":"response-transformer",
"config":{"add":{"headers":["X-Lab:Trainingslager"]}}}' -o ch.yaml
deck gateway diff ch.yaml | grep -E '^creating|Created'
cp ch.yaml ~/kong-lab/kong/kong.yaml && kreload
curl -si -H 'Host: echo.lab' $PROXY/get | grep -i '^x-lab'
curl -si $PROXY/echo/get | grep -i -c '^x-lab'Expected:
creating plugin response-transformer for route echo-host
Created: 1
Kong reloaded
X-Lab: Trainingslager
0
Then go back to the final state:
git -C ~/kong-lab/kong checkout kong.yaml && kreload.
Save your progress? Sign up for free
Enterprise Note
- Changing the order: Kong Enterprise allows
orderingper plugin (dynamic ordering). In the free edition, only the fixed priority applies. - Distributed cache:
strategy: memoryapplies per Kong node. Several nodes have separate caches; Enterprise offersproxy-cache-advancedwith Redis. - CORS belongs either in the gateway or in the backend, never in both; duplicate headers break browsers.
- Maintenance windows as a prepared, inactive plugin in Git: switching it on is then a small, reviewable commit.
- Plugin Hub: Besides the 45 bundled ones there are community plugins; every third-party plugin runs with full privileges in the gateway and needs to be reviewed.