I need to add the a custom header to the ElementAPI endpoints I setup but I want to avoid editing the source of the plugin. What is the best way to go about this?

The ElementAPI plugin returns some default headers by using:


To quickly achieve what I needed I added the following to the ElementApiControllor.php:

HeaderHelper::setHeader(['Surrogate-Control: max-age=300'])

This works for now but I'd love to learn how to extend existing plugins that don't have any documented hooks with my own if it is possible.

2 Answers 2


You can do this by assigning your endpoint(s) to a function:

return [
    'endpoints' => [
        'my-endpoint' => function() {
            HeaderHelper::setHeader(['Surrogate-Control: max-age=300']);

            return [
                // ...


Alternatively as of v1.2, you can do it from a separate plugin using the onBeforeSendData event:

public function init()
    craft()->on('elementApi.onBeforeSendData', function(Event $event) {
        HeaderHelper::setHeader(['Surrogate-Control: max-age=300']);
  • This is great! if I already have 30+ endpoints setup, is there a better way to share this across all of them? No worries if not, I can copy/paste. Just curious.
    – Paulo
    Commented Apr 2, 2016 at 1:12
  • 1
    @Paulo Just released v1.2 with a new onBeforeSendData event that will give you a DRY way to do this. Updated my answer with details. Commented Apr 2, 2016 at 13:54
  • Yes! I'll give it a try today
    – Paulo
    Commented Apr 2, 2016 at 16:44

In case anyone finds this in a Google search, this is how you'd do it in Craft 3, if, say, you wanted to add an Expires header:

$response = Craft::$app->getResponse();
$response->headers->set('Expires', gmdate('D, d M Y H:i:s \G\M\T', strtotime("+1 month")));

Yii2 Responses

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.