Deno nuggets: HTTP headers

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to get/set HTTP headers from/in Request/Response?

> curl http://localhost:5000 -H 'x-custom-hdr: VAL-123'
GET / HTTP/1.1
Host: localhost:5000
User-Agent: curl/7.64.1
Accept: */*
x-custom-hdr: VAL-123

HTTP/1.1 200 OK
cache: no-cache
x-custom-hdr: VAL-123
content-type: text/plain;charset=UTF-8
content-length: 5

Hello

Solution

Both the Request & Response objects implements web standard Headers API. Therefore, getting/setting headers is the same for Request or Response.

//Base codeimport { serve } from "https://deno.land/std/http/mod.ts";async function reqHandler(req: Request) {
//Get & set headers
return new Response("Hello World!");
}
serve(reqHandler, { port: 8000 });

Imports

No imports are required.

Check header exists

The has function can be used to check if a header is present or not:

req.headers.has('x-custom-hdr'); //true
req.headers.has('x-abc-hdr'); //false

Get a single header

The get function can be used to get the value for a given header name (CSV is returned only if there are multiple headers with the same name):

req.headers.get('user-agent'); //curl/7.64.1
req.headers.get('x-custom-hdr'); //VAL-123
req.headers.get('x-abc-hdr'); //null

Get all headers

The entries function can be used to iterate over all the headers:

for(const h of req.headers.entries())
h;
[ "accept", "*/*" ]
[ "host", "localhost:5000" ]
[ "user-agent", "curl/7.64.1" ]
[ "x-custom-hdr", "VAL-123" ]

Set header

There are multiple ways to set header:

  • 1. Set directly on the Request/Response object
new Response('hello', {
headers: {
'x-some-hdr': 'val-some-hdr',
someHeader: 'someValue'
}
}
  • 2. Set in a separate header object & then give it to Response object:
const headers=new Headers();
headers.set('HDR1', 'VHDR1');
headers.set('HDR2', 'VHDR2');
new Response('hello', {headers});

Append header

The append function is similar to set, except that it allows setting duplicate header names. The output would be a CSV of all duplicate headers.

const headers=new Headers();
headers.append('HD', 'V');
headers.append('HD', 'V1');
new Response("Hello World!", {headers});
//hd: V, V1

Complete code

Here is the complete code of the example shown in the introduction section:

import { serve } from "https://deno.land/std/http/mod.ts";async function reqHandler(req: Request) {
const ch=req.headers.get("x-custom-hdr");
const headers=new Headers({
cache: "no-cache"
});
ch && headers.set("x-custom-hdr", ch);
return new Response("Hello", {headers});
}
serve(reqHandler, { port: 8000 });

--

--