Is there a way to get the user's IP address in a twig template? All the twig examples I find say to do it like this:

{% set ipAddr = app.request.server.get("REMOTE_ADDR") %}

But this variable always returns NULL. These examples aren't specific to Drupal so I'm guessing part of the Drupal implementation blocks/omits this.

  • Preprocess the template and get the IP that way?
    – Kevin
    Commented Nov 30, 2017 at 19:21
  • That's exactly the solution that I ended up going with as shown below. Commented Nov 30, 2017 at 21:59

1 Answer 1


Suppose you want to get the ip in the page.html.twig file.

in your


you can try

use Symfony\Component\HttpFoundation;

function YOURTHEME_preprocess_page(&$variables) {
  $variables['page']['ip'] = \Drupal::request()->getClientIp();


in your template


you can try:

{{ page.ip }}

  • That worked perfectly. I had just found the xxx.theme file and was working on a preprocess function when I saw your answer. Thanks! Commented Nov 30, 2017 at 20:00
  • This doesn't work for me because of drupal cache system...
    – Sky
    Commented Dec 24, 2017 at 23:36
  • As time has progressed I've noticed that @Sky is correct, Drupal will generate an IP the first time the template is loaded and then cache that IP. Any future users will see the cached IP instead of their own. Commented May 24, 2018 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.