Skip to main content

httpresponse.header(headerName, headerValue)

Adds an HTTP header to the response object

Availability

Agent

Parameters

Name Type Description
headerName String The header’s name (key) without the colon (":")
headerValue String The header’s value

Returns

Nothing

Description

This method adds an HTTP header to the target httpresponse object. All the headers you wish to include with the response must be added before httpresponse.send() is called it issue the response.

The Content-Length header is set automatically.

Cookies

Among the standard headers which may be added to a response is Set-Cookie. If you wish to use this header, be aware that unless you restrict the cookie by path, its contents will be accessible to a browser when it contacts any other agent. This is because all agents exist in the same domain, agent.electricimp.com.

To override this behavior, limit the scope of your cookie to a single agent. Do this by adding a path field to the definition of the cookie in your agent code:

response.header("Set-Cookie", "cookie=SOME_DATA ; path=/<agent ID>")

where <agent ID> is the part of the agent’s URL after the domain:

https://agent.electricimp.com/<agent ID>

Developers can see the ID of a development device’s agent in impCentral™, but production devices’ agent IDs are not accessible this way. Instead, your agent code should contain functionality to determine a given instance’s ID and apply it to the Set-Cookie header. See the second example, below, for one method for making this happen.

  • For more information on how cookies operate, see Wikipedia.

Example Code

This code shows a typical HTTP request handler which modifies the automatically generated HTTP response and then sends the response back to the source of the original request.

The following code shows how to secure a `Set-Cookiea header by adding the agent’s own unique ID to the cookie’s path variable. This will limit access to the cookie generated with this ID to this agent only.