Setting HTTP Headers

Chapter 11: How to set HTTP status and HTTP response headers with meta objects

When a new HTTP or WebSocket connection is made, you might want to set the HTTP status or HTTP headers, such as Set‑Cookie, in the response to the client. This can be done by including meta objects in the response to auth, access or call requests. Let’s learn how to do it!

HTTP and WebSocket connection

The payload for an auth request1, call request2, or access request3 may contain a parameter, isHttp, that can be set to true. This value is set by Resgate when a client has made an HTTP or WebSocket connection that has yet to be responded to by Resgate.

  • For client HTTP GET requests, the access request will have isHttp set to true.
  • For client HTTP POST requests, both the access request and the call request will have isHttp set to true.
  • For both client HTTP GET and POST request, if --headauth is configured, the resulting auth request will have isHttp set to true.
  • For WebSocket connections, if --wsheadauth is configured, the resulting auth request will have isHttp set to true.

Meta objects

If the isHttp parameter of a request is set to true, the response4 may include an optional meta property containing a meta object5. This object may include an HTTP status code6 and additional HTTP headers we wish to include in the HTTP or WebSocket response.

Example

A response to an auth request, trying to set cookies, could look like this:

{
	"result": nil,
	"meta": {
		"header": {
			"Set-Cookie": [
				"authToken=SGkgdGhlcmUh; HttpOnly; Secure; Expires=Wed, 21 Oct 2015 07:28:00 GMT",
				"sessionId=e8bb43229de9; Domain=foo.example.com",
			]
		}
	}
}

Example

A response to an access request, giving a custom HTTP status error code, can look like this:

{
	"error": {
		"code": "authService.paymentRequired",
		"message": "Paying members only."
	},
	"meta": {
		"status": 402
	}
}

Note

For 4XX and 5XX status codes, any error set on the response will be used. If no error is set, Resgate will return a generic error matching the status code.

Example

A response to a call request, trying to redirect to another page, could look like this:

{
	"result": nil,
	"meta": {
		"status": 303,
		"header": {
			"Location": [ "https://example.com/redirect/url" ]
		}
	}
}

Note

Any 3XX status is not recommended for WebSocket connections as WebSocket clients tend to ignore it.