How to add a cookie when using TYPO3 Middleware?

622 views Asked by At

I want to use the Middleware to add a cookie.

In TYPO3 I have the Psr\Http\Message\ServerRequestInterface $request and the Psr\Http\Server\RequestHandlerInterface $handler variables.

What is the best practise to add a cookie with all the needed settings (secure, domain, expire)?

2

There are 2 answers

0
Mathias Brodala On BEST ANSWER

There is no explicit interface in PSR for this since it basically boils down to sending a Set-Cookie header in the $response. You can either build that header yourself or use some packages which do this for you:

0
Thomas Löffler On

My working code is now:

$cookie = \Dflydev\FigCookies\SetCookie::create($name)
    ->withValue($value)
    ->withDomain($request->getAttribute('site')->getBase()->getHost())
    ->withSecure(true);

$response = new \TYPO3\CMS\Core\Http\RedirectResponse(
    (string)$request->getUri(),
    302,
    ['Set-Cookie' => (string)$cookie]
);

The cookie is set and I redirect the visitor so the cookie can also be read out by e.g. a TypoScript condition.