How to Set Cookies in CasperJS
Set cookies in CasperJS with PhantomJS’s page.addCookie API, verify failures, avoid domain traps, and understand this legacy stack.

Use CasperJS’s underlying PhantomJS WebPage object: call this.page.addCookie(cookie) inside a CasperJS navigation step, then check its Boolean return value. The cookie domain must match the page you are visiting or PhantomJS may reject it.
CasperJS is no longer actively maintained, so validate this approach against the CasperJS and PhantomJS versions installed in your environment. The official CasperJS project describes Casper as a navigation utility for PhantomJS, and its page property exposes the underlying WebPage instance. CasperJS project · PhantomJS addCookie API
Minimal working example
var casper = require('casper').create();
casper.start('https://example.com/', function () {
var added = this.page.addCookie({
name: 'session',
value: 'abc123',
domain: 'example.com',
path: '/',
secure: true,
httponly: true
});
this.echo('Cookie added: ' + added);
});
casper.run();
addCookie returns true when PhantomJS accepts the cookie and false when it does not. The values above are placeholders; replace the host, cookie name, value, and attributes with those required by the target site.
How cookie setting works in CasperJS
- Create a Casper instance with
require('casper').create(). - Start at a URL on the cookie’s target domain.
- Call
this.page.addCookie(cookie)in the navigation callback. - Check the returned Boolean and stop or report a useful error if it is
false. - Continue with navigation or interaction that depends on the cookie.
The call is made through PhantomJS, not through the page’s DOM. That distinction matters for attributes such as httponly, which page JavaScript cannot create.

Cookie object fields
| Field | Purpose | Practical guidance |
|---|---|---|
name |
Cookie name | Required. Use the exact name expected by the site. |
value |
Cookie value | Required. Keep the value in the format the application expects. |
domain |
Host scope | Use a domain matching the current page. A mismatch can cause rejection. |
path |
URL path scope | Use / when the cookie should apply throughout the site. |
secure |
HTTPS-only flag | Set it when the cookie is intended for HTTPS requests. |
httponly |
Blocks page JavaScript access | Set it for server-managed session cookies when appropriate. |
expires or expiry |
Expiration time | Supply it only when you need a persistent expiration. |
The documented PhantomJS cookie structure includes domain, expires/expiry, httponly, name, path, secure, and value. See the addCookie documentation for the API contract.
Set a cookie before opening the protected page
If the site requires a cookie before its first authenticated request, begin CasperJS at a URL on the same host, add the cookie in that callback, and then open the destination:
var casper = require('casper').create();
var cookieAdded = false;
casper.start('https://example.com/', function () {
cookieAdded = this.page.addCookie({
name: 'session',
value: 'replace-with-session-value',
domain: 'example.com',
path: '/',
secure: true,
httponly: true
});
if (!cookieAdded) {
this.die('PhantomJS rejected the cookie');
}
});
casper.thenOpen('https://example.com/account', function () {
this.echo('Account page loaded: ' + this.getTitle());
});
casper.run();
Starting on the matching host makes the domain relationship explicit. If the application uses a subdomain, choose the domain that the site actually sets and that PhantomJS accepts for the current URL.
Inspect cookies visible to the current URL
PhantomJS exposes page.cookies, an array containing cookies visible to the current URL. Use it after navigation to inspect what the page can see:

casper.then(function () {
this.echo(JSON.stringify(this.page.cookies, null, 2));
});
Use page.addCookie to set a cookie; use page.cookies to inspect the cookie jar for the current URL. The PhantomJS cookies property documents the readable fields.
addCookie versus casper.evaluate
casper.evaluate() runs JavaScript inside the remote page, as if entered in that page’s browser console. It is a different mechanism from the WebPage API and cannot create an HttpOnly cookie. For HttpOnly or other explicit cookie attributes, call this.page.addCookie() instead.
// Page-context cookies are limited to what document.cookie permits.
casper.then(function () {
this.evaluate(function () {
document.cookie = 'theme=dark; path=/';
});
});
Prefer the WebPage API when you need a predictable domain, path, secure flag, HttpOnly flag, or expiration.
Common failures and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
addCookie returns false |
The cookie domain does not match the current page, or an attribute is invalid. | Start on the target host, use the site’s actual domain, simplify the object, and check the Boolean result. |
| Cookie appears in code but the site still redirects to login | The value is expired, incomplete, scoped to another path, or tied to a server-side session. | Obtain a valid value, use path: '/' when appropriate, and verify the server recognizes the session. |
| Cookie is missing on a subdomain | The domain or path does not cover that URL. | Set the cookie for the host and path used by the request, then inspect this.page.cookies after navigation. |
| HTTPS request does not receive the cookie | secure was set incorrectly or the page is not HTTPS. |
Match the flag to the site’s expected transport and test on the same scheme. |
| Page JavaScript cannot read the cookie | The cookie was marked httponly. |
This is expected. Read it from server behavior or inspect the WebPage cookie list instead. |
| Modern site fails despite a correct cookie | CasperJS and PhantomJS are legacy tools and may not support the site’s browser requirements. | Confirm the installed versions, simplify the test, and consider a maintained browser automation stack. |
Debugging checklist
- Print the return value from
this.page.addCookie(). - Confirm the URL host and cookie domain match.
- Confirm the path covers the destination URL.
- Check whether the cookie is expired or dependent on a server-side session.
- Inspect
this.page.cookiesafter navigation. - Verify whether the site requires HTTPS, JavaScript features, or browser behavior PhantomJS does not provide.
- Check the installed CasperJS and PhantomJS versions; the CasperJS project is no longer actively maintained.
Performance, reliability, and maintenance
Adding a cookie is a local WebPage operation; the expensive part is loading the target page and waiting for its requests. Keep the cookie object minimal, set it before the navigation that needs it, and avoid repeated browser launches when one CasperJS process can perform several related steps.
Reliability depends on the target application as well as the cookie. A session cookie may expire, be revoked, depend on an IP or user agent, or require additional cookies. Treat a successful addCookie return value as acceptance by PhantomJS, not proof that the server will authenticate the request.
Because CasperJS is no longer actively maintained, modern sites may fail for reasons unrelated to cookie syntax. Record the tool versions and validate the complete login or navigation flow against the actual site.
Or skip the browser setup
If your goal is a clean screenshot after supplying a URL, ScreenshotNeo provides a single GET request and supports custom cookies, headers, user agents, authorization, waits, JavaScript, and other capture controls. Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed.
See the ScreenshotNeo API documentation for the current parameter list.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo reports whether a response was a clean billed shot through the X-Page-Verdict and X-Billed headers. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
FAQ
Where should I call addCookie?
Call this.page.addCookie(cookie) in a CasperJS navigation callback before the request or interaction that needs the cookie.
Does addCookie throw an error when it fails?
The documented API returns a Boolean. Capture the value and handle false explicitly.
Can casper.evaluate set an HttpOnly cookie?
No. Page JavaScript cannot create an HttpOnly cookie; use the underlying PhantomJS WebPage API.
Why does a correct-looking cookie not log me in?
The cookie may be expired, scoped incorrectly, tied to server-side state, or insufficient for the site’s authentication flow. Verify the cookie jar and the server response.
Is CasperJS suitable for new projects?
It is a legacy stack. The official project states that CasperJS is no longer actively maintained, so evaluate a maintained browser automation tool for new work.


