HTTP headers contain extra information that are sent together with an HTTP request or response. They provide context, instructions, and metadata that help browsers and servers communicate effectively. These information can be used to manage authentication, sessions, cross-origin resource sharing (CORS) and more. They also provide important information about the request or response, such as the content type, content length, authentication credentials, and more. HTTP headers are made up of case-insensitive key value pairs. HTTP headers play a very important role in client server communication and also enable developers customize the behavior of their API.
HTTP headers can be grouped according to their context
Request headers
The request headers is sent by the client to the server. Request headers contain extra information about the data to be fetched or about the client making the request. Examples of commonly used request headers are
Accept
: This contains the type of media or MIME types that the client can accept from the server. The accept key contains one or more value. The most commonly used accept headers areaccept: application/json
andaccept: text/html
, these values indicates that the client wants to accept data in JSON or HTML format. Other values includeaccept: */*
this indicates that the server can accept any MIME typeContent-type
: The content type defines the MIME type of data sent to the server. TheContent-Type: application/json
tells the server that the data coming in is in JSON format another example isContent-Type: multipart/form-data
this lets the server know that a form is sent.User-Agent
: This carries information about the clients application or browser exampleUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36
tells the server that the request is coming from a Chrome browser installed on a windows machine
Response headers
The response header is sent from the server to the clients. Response headers contain extra information about the data returned from the server and also information about the server.
Content-type
: The content type defines the MIME type of data returned to the client. This lets the client know how to interpret the incoming data.Location
: This header is used to redirect the client to a new URL. This is only useful when the status code is3xx
or201
.Cache-control
: This controls the caching behaviour of browser like when the content should be cached, when the cached content expires and when it is revalidated. Example the value ofpublic
allows caching by any caching client, the value ofprivate
allows caching only by the browser,no-cache
means that the response should not be cached,max-age
tells the browser or the caching client how long the response should be cached
Cookie headers
Cookie headers are used to send cookies between the server and the client. These cookies contain pieces of information about the client e.g the client's session and preferred settings. This headers plays an important role in delivering personalized experience to the client.
Set-cookie
: This header is used to send cookies from the server to the client and also store the cookie on the browser.Cookie
: This is used to send the cookie stored by theSet-cookie
header to the server
Cors headers
Cors headers are used to manage cross-origin resource sharing(CORS). This gives servers the ability to determine origins that can access their resources and the http methods that can be used to access those resources. CORS helps prevent cross-site scripting (XSS) and other security vulnerabilities.
Access-Control-Allow-Origin
: This specifies the origin(s) that can access the resource. This can be a single origin or list of origins exampleAccess-Control-Allow-Origin: https.example.com
or a wildcard that means that it can be accessed by any originAccess-Control-Allow-Origin: *
Access-Control-Allow-Methods
: This is the list of http methods that can be used the access the resource. ExampleGET
,POST
,PUT
andDELETE
.Access-Control-Allow-Headers
: This is the list of headers and custom headers that can be used when making a request to access the resourceAccess-Control-Allow-Credentials
: This headers tells the browser or client if the server allows cross-origin requests that contain credentials. These credentials can be authentication headers, cookies.
Authentication headers
The authentication header is used for authentication and authorization during http communication between and server and a client. This allows the client to access protected resources that are part of the web service.
WWW-authenticate
: This header determines the authentication method(challenge) that will be used to gain access to a protected resource. After receiving thewww-authenticate
header the browser would ask the user for credentials and then fetch the resource again.Authorization
: The authorization header is used to send authentication credentials to the server. it commonly sends a username and a password or a token for authentication, these credentials are base-64 encoded in the case of a username and password e.gAuthorization: Basic dG9tOm15cGFzc3dvcmQ=
.
How to set headers from client
To set http headers from the client, it is done while making a http request using javascript fetch
or axios
.
await fetch("https://api.example.com", {
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer eyJhbGciOi...",
"Accept": "application/json"
},
method: "POST",
body: JSON.stringify({
title: "Hello Tutorial",
})
});
In the example above we are making a post request to https://api.example.com
. The headers contain extra information about our request. The type of content we are sending is a json data, the client is also expecting to get a response in the same json format, we also have an authorization header which the server would use to authenticate the client making this request.
How to set headers from server
In this example we are going to use Node.js and express.js. Node.js is a javascript runtime for building backend applications, express.js is a node.js framework used to build server applications.
app.get("/", (request, response) => {
response.set({
test: "This is a test header",
"Extra-header": "This is an extra header",
});
response.send("Hello world");
});
To set the headers in this express GET
request route, we use response.set()
which takes in an object with the headers that we want to set, the key is the name of the header while the value is the parameters or value the header. The response.set()
can also take the name of the header as the first argument and the values or details as the second.
conclusion
In this tutorial we learnt about http headers, various categories of http headers and how to set custom headers both on the client and the server. Http headers play important role in our server-client communication. By using authentication and CORS headers we can improve the security of our application. If you are a beginner you can learn more about HTTP by learning about http methods and http status codes. The knowledge of these would help you become a better developer. Thanks for reading. HAPPY CODING!