Laravel 11 web api when we use HttpOnly then cookies aren't being sent with that request, what can be done to make sure Laravel sends HttpOnly cookies with each request?
When using Laravel 11 for building a web API and setting the HttpOnly flag for cookies, you might encounter an issue where cookies aren't being sent with each request. This can lead to authentication and session issues. To ensure that Laravel sends HttpOnly cookies with each request, follow these steps:
- Set the HttpOnly flag when creating the cookie:
In your Laravel controller or middleware, when creating a new cookie, make sure to set the HttpOnly flag by passing an array with the secure
and httpOnly
keys:
$cookie = cookie('token', $token, 60 * 24 * 30); // token is your actual token value
$cookie->secure(); // Set secure flag
$cookie->httpOnly(); // Set HttpOnly flag
return response()->json(['token' => $cookie->toString()]);
- Set the
SESSION_COOKIE_DOMAIN
andCSRF_COOKIE_DOMAIN
configuration values:
If you're using subdomains for your API and your session or CSRF cookies are not being sent, you need to set the SESSION_COOKIE_DOMAIN
and CSRF_COOKIE_DOMAIN
configuration values in your .env
file:
SESSION_COOKIE_DOMAIN=api.example.com
CSRF_COOKIE_DOMAIN=api.example.com
Replace api.example.com
with your actual API subdomain.
- Use the
withCookie()
method in your API responses:
If you're returning a response with cookies and you want to ensure that the HttpOnly flag is set, use the withCookie()
method:
return response()->json(['data' => $data], 200)
->withCookie(cookie('token', $token, 60 * 24 * 30)
->secure()
->httpOnly());
- Use the
Cookie
facade to set and send cookies:
You can also use the Cookie
facade to set and send cookies with the with
method in your controller or middleware:
use Illuminate\Http\Cookie;
// ...
$cookie = new Cookie('token', $token, 60 * 24 * 30);
$cookie->secure();
$cookie->httpOnly();
return response()->json(['data' => $data], 200)
->withCookie($cookie);
By following these steps, you should be able to ensure that Laravel sends HttpOnly cookies with each request in your Laravel 11 web API.