TYPO3 set a cookie within a controller action

Viewed 32

I try to set a cookie in a regular controller action which is called via typenumcall. I am on TYPO3 v 10.4

public function redirectCookieAction(): ResponseInterface
{
    //do magic stuff...      

    /** @var \TYPO3\CMS\Core\Http\Response $response */
    $response = GeneralUtility::makeInstance(ResponseFactory::class)->createResponse(200);
    $response->withHeader('Set-Cookie', 'cookiename' . '=' . 'cookievalue' . '; Path=/; Max-Age=' . (time()+60*60*24*30));
    return $response;
}

I try to use the PSR7-HTTP-Response but for some reason the cookie isn't set after calling the action. It seems like the $response object is completely ignored. How do I use the ResponseInterface correctly?

I already saw this thread but it im not in a middleware and also don't have a fe_session at this point: TYPO3 how to set custom cookie inside a form finisher

1 Answers

Since the $response returns a new instance of itself, you must assign it to a variable, like this

/** @var \TYPO3\CMS\Core\Http\Response $response */
$response = GeneralUtility::makeInstance(ResponseFactory::class)->createResponse(200);
$response = $response->withAddedHeader('Set-Cookie', 'cookiename' . '=' . 'cookievalue' . '; Path=/; Max-Age=' . (time()+60*60*24*30));
return $response;
Related