|
| 1 | +--- |
| 2 | +layout: tutorial |
| 3 | +official: false |
| 4 | +title: Javalin Cloudflare Proxy Support |
| 5 | +permalink: /tutorials/javalin-cloudflare-proxy-support |
| 6 | +summarytitle: Using Javalin with Cloudflare |
| 7 | +summary: Learn how to make Javalin work with Cloudflare. |
| 8 | +date: 2026-02-07 |
| 9 | +author: <a href="https://github.com/AoElite">AoElite</a> |
| 10 | +language: ["java"] |
| 11 | +rightmenu: true |
| 12 | +--- |
| 13 | + |
| 14 | +## Introduction |
| 15 | + |
| 16 | +When using Cloudflare to proxy requests to your Javalin application, it's important to configure Javalin to correctly |
| 17 | +to handle Cloudflare's headers, along with configuring your environment to only allow traffic from Cloudflare to your |
| 18 | +application. |
| 19 | + |
| 20 | +## Configuring Javalin to resolve real IP addresses |
| 21 | +To configure Javalin to resolve real IP addresses, you can use the `contextResolver.ip` configuration option to provide |
| 22 | +a function that resolves the IP address from the request. |
| 23 | + |
| 24 | +Here's how to configure it to use Cloudflare's headers to |
| 25 | +resolve the IP address: |
| 26 | +```java |
| 27 | +Javalin javalin = Javalin.create(config -> config.contextResolver.ip = (Function1<Context, String>) ctx -> { |
| 28 | + String cfHeader = ctx.header("CF-Connecting-IP"); |
| 29 | + return (cfHeader != null && !cfHeader.isBlank()) ? cfHeader : ctx.req().getRemoteAddr(); // fallback if blank |
| 30 | + }).start(); |
| 31 | +``` |
| 32 | + |
| 33 | +Now when invoking the `ip()` method from a `Context` instance, it will return the actual IP address of the client. |
| 34 | + |
| 35 | +## Only allowing traffic from Cloudflare |
| 36 | +It's important to only allow traffic to your application from Cloudflare, otherwise the headers could be forged. |
| 37 | + |
| 38 | +There's a few ways you can do this: |
| 39 | + |
| 40 | +### Using UFW Firewall rules |
| 41 | +You can find instructions and a script to automatically configure Cloudflare IP addresses with UFW in |
| 42 | +[this GitHub repository](https://github.com/Paul-Reed/cloudflare-ufw). |
| 43 | + |
| 44 | +### Docker and Cloudflare Tunnels |
| 45 | +You can configure the port that Javalin uses to be bound to a local interface within docker, and then use a Cloudflare |
| 46 | +Tunnel to proxy requests to that port so that only Cloudflare can access it. You can find more information about |
| 47 | +Cloudflare Tunnels on [Cloudflare's website](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/). |
| 48 | + |
| 49 | +### Configuring Javalin to only allow traffic from Cloudflare (not recommended) |
| 50 | +You can also configure Javalin to only allow traffic from Cloudflare IPs by checking the remote address before resolving |
| 51 | +the header; however, this would still open up your application to DDOS attacks. |
0 commit comments