Bare Docs
ReferenceBareModules

bare-https

HTTPS library for JavaScript

Documented against v3.1.0
stable

bare-https — HTTPS library for JavaScript.

Mirrors the Node.js https module.

npm i bare-https

Usage

const https = require('bare-https')

const options = {
  cert: fs.readFileSync('test/fixtures/cert.crt'),
  key: fs.readFileSync('test/fixtures/cert.key')
}

const server = https.createServer(options, (req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Length', 10)
  res.write('hello world!')
  res.end()
})

server.listen(0, () => {
  const { port } = server.address()
  console.log('server is bound on', port)

  const client = https.request({ port }, (res) => {
    res.on('data', (data) => console.log(data.toString()))
  })
  client.end()
})

API

HTTPSSocket

HTTPSSocket._destroy(err: Error | null, cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
errError | null
cbStreamCallback

HTTPSSocket._final(cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
cbStreamCallback

HTTPSSocket._open(cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
cbStreamCallback

HTTPSSocket._predestroy(): void

_read(size: number): void

Parameters

ParameterTypeDefaultDescription
sizenumber

HTTPSSocket._write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
dataunknown
encodingStreamEncoding
cbStreamCallback

HTTPSSocket._writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
batch{ chunk: unknown; encoding: StreamEncoding }[]
cbStreamCallback

address(): TCPSocketAddress | null

alpnProtocol: string | null

HTTPSSocket.closed: boolean

connect

connect(port: number, host?: string, opts?: TCPSocketConnectOptions, onconnect?: () => void): this

Connect the socket to port on host. If host is not provided, it defaults to 'localhost'. onconnect is called when the connection is established.

Parameters

ParameterTypeDefaultDescription
portnumberThe port to connect to.
host?stringThe host to connect to; defaults to 'localhost'.
opts?TCPSocketConnectOptionsConnection options; if host is a hostname it is resolved with opts.lookup, which defaults to dns.lookup from bare-dns.
onconnect?() => voidCalled when the connection is established.

Throws

  • SOCKET_ALREADY_CONNECTED — the socket is already connecting or connected.
  • INVALID_PORTport is not an integer between 0 and 65535.

connecting: boolean

Whether the socket is currently connecting.

HTTPSSocket.cork(): void

HTTPSSocket.destroy(err?: Error | null): void

Parameters

ParameterTypeDefaultDescription
err?Error | null

HTTPSSocket.destroyed: boolean

HTTPSSocket.destroying: boolean

encrypted: true

HTTPSSocket.end(cb?: StreamCallback): this

Overloads:

end(cb?: StreamCallback): this
end(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): this
end(data: unknown, cb?: StreamCallback): this

Parameters

ParameterTypeDefaultDescription
cb?StreamCallback

HTTPSSocket.errored: Error | null

HTTPSSocket.keepAlive: boolean

keepAliveInitialDelay: number

localAddress: string

The local IP address of the socket, if connected.

localFamily: string

The local IP family ('IPv4' or 'IPv6'), if connected.

localPort: number

The local port of the socket, if connected.

noDelay: boolean

open(fd: number, opts?: TCPSocketOpenOptions, onconnect?: () => void): this

Open the socket on the file descriptor of an existing TCP connection, emitting 'connect' once open.

Overloads:

open(fd: number, opts?: TCPSocketOpenOptions, onconnect?: () => void): this
open(fd: number, onconnect: () => void): this
open(opts: TCPSocketOpenOptions & { fd: number }, onconnect?: () => void): this

Parameters

ParameterTypeDefaultDescription
fdnumberThe file descriptor of an existing TCP connection to open the socket on.
opts?TCPSocketOpenOptionsfd may be given here instead of as the first argument.
onconnect?() => voidCalled once when the socket emits 'connect'.

pause(): this

pending: boolean

Whether the socket has not yet connected.

pipe<S extends Writable>(dest: S, cb?: StreamCallback): S

Parameters

ParameterTypeDefaultDescription
destS
cb?StreamCallback

push(data: unknown | null, encoding?: BufferEncoding): boolean

Parameters

ParameterTypeDefaultDescription
dataunknown | null
encoding?BufferEncoding

read(): unknown | null

HTTPSSocket.readable: boolean

readyState: 'open' | 'opening' | 'readOnly' | 'writeOnly' | 'closed'

The current state of the socket.

ref(): this

Ref the socket, preventing the process from exiting.

remoteAddress: string

The remote IP address of the socket, if connected.

remoteFamily: string

The remote IP family ('IPv4' or 'IPv6'), if connected.

remotePort: number

The remote port of the socket, if connected.

resume(): this

setEncoding(encoding: BufferEncoding): void

Parameters

ParameterTypeDefaultDescription
encodingBufferEncoding

setKeepAlive(enable?: boolean, delay?: number): this

Enable or disable keep-alive. delay is the initial delay in milliseconds before the first keep-alive probe is sent.

Overloads:

setKeepAlive(enable?: boolean, delay?: number): this
setKeepAlive(delay: number): this

Parameters

ParameterTypeDefaultDescription
enable?boolean
delay?number

setNoDelay(enable?: boolean): this

Enable or disable Nagle's algorithm. When enable is true (the default), data is sent immediately without buffering.

Parameters

ParameterTypeDefaultDescription
enable?boolean

HTTPSSocket.setTimeout(ms: number, ontimeout?: () => void): this

Set a timeout in milliseconds. When the socket is idle for ms milliseconds, a timeout event is emitted. Pass 0 to disable the timeout.

Parameters

ParameterTypeDefaultDescription
msnumber
ontimeout?() => void

socket: Duplex

timeout: number

The timeout in milliseconds, or undefined if no timeout is set.

HTTPSSocket.uncork(): void

unref(): this

Unref the socket, allowing the process to exit.

unshift(data: unknown | null, encoding?: BufferEncoding): boolean

Parameters

ParameterTypeDefaultDescription
dataunknown | null
encoding?BufferEncoding

HTTPSSocket.writable: boolean

HTTPSSocket.write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean

Overloads:

write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
write(data: unknown, cb?: StreamCallback): boolean

Parameters

ParameterTypeDefaultDescription
dataunknown
encoding?BufferEncoding
cb?StreamCallback

HTTPSAgent

addRequest(req: HTTPClientRequest, opts: TCPSocketOptions & TCPSocketConnectOptions): void

Assigns a socket to req, reusing an idle keep-alive socket for the same origin if one is available, creating a new one if there is room, and queueing the request until one comes free otherwise.

Parameters

ParameterTypeDefaultDescription
reqHTTPClientRequestThe request to assign a socket to.
optsTCPSocketOptions & TCPSocketConnectOptionsThe socket and connection options, including the destination host and port.

createConnection(opts?: HTTPSSocketOptions): HTTPSSocket

Creates a new HTTPSSocket connection wrapping a plain TCP connection in TLS.

Parameters

ParameterTypeDefaultDescription
opts?HTTPSSocketOptionsOptions for the underlying TCP connection and its TLS wrapper.

defaultPort: number

The port used for a request that names none.

destroy(): void

Destroys all sockets currently held by the agent, both in-use and free.

freeSockets: IterableIterator<TCPSocket>

An iterator over the agent's idle, keep-alive sockets awaiting reuse.

getName(opts: TCPSocketConnectOptions): string

Returns the pool key used to group sockets by destination, derived from opts.host, opts.port, opts.localAddress, opts.family, and opts.socketPath.

Parameters

ParameterTypeDefaultDescription
optsTCPSocketConnectOptionsThe connection options to derive the pool key from.

HTTPSAgent.global: HTTPSAgent

The agent's own default instance (created with keepAlive: 1000 and timeout: 5000), used as bare-https's globalAgent.

HTTPSAgent.keepAlive: boolean

Whether the agent keeps sockets open for reuse once a request completes.

keepSocketAlive(socket: TCPSocket): boolean

Marks socket to be kept alive and unreferenced instead of closed once a request completes. Returns whether the socket was kept alive.

Parameters

ParameterTypeDefaultDescription
socketTCPSocketThe socket to keep alive for reuse.

maxFreeSockets: number

How many sockets the agent may keep in its pool for a single origin once they are free.

maxSockets: number

How many sockets the agent may hold at once for a single origin.

maxTotalSockets: number

How many sockets the agent may hold at once across every origin it talks to.

resume(): void

Resumes an agent suspended with suspend(), allowing it to create connections again.

resumed: Promise<void> | null

A promise that resolves once a suspended agent is resumed, or null if the agent isn't suspended.

reuseSocket(socket: TCPSocket, req?: HTTPClientRequest): void

Marks socket as back in active use, referencing it so it keeps the event loop alive.

Parameters

ParameterTypeDefaultDescription
socketTCPSocketThe socket to mark as back in active use.
req?HTTPClientRequestThe request the socket is being reused for.

sockets: IterableIterator<TCPSocket>

An iterator over all sockets currently held by the agent, both in-use and free.

suspend(): void

Suspends the agent, destroying all its sockets and preventing new connections until resume() is called.

suspended: boolean

Whether the agent is currently suspended.

HTTPSServer

HTTPSServer

new HTTPSServer(opts?: HTTPSServerOptions, onrequest?: (req: HTTPIncomingMessage, res: HTTPServerResponse) => void)

An HTTPS server, reusing bare-http1's request parsing and response handling over HTTPSSocket connections instead of plain TCPSocket connections.

Parameters

ParameterTypeDefaultDescription
opts?HTTPSServerOptionsServer options: TLS socket options (for example cert, key) plus bare-http1 server connection options.
onrequest?(req: HTTPIncomingMessage, res: HTTPServerResponse) => voidAdded as a 'request' listener.

HTTPSClientRequest

new HTTPSClientRequest(opts?: HTTPSClientRequestOptions, onresponse?: () => void)

An outgoing HTTPS request, extending bare-http1's HTTPClientRequest but defaulting to an HTTPSAgent instead of an HTTPAgent.

Overloads:

new HTTPSClientRequest(opts?: HTTPSClientRequestOptions, onresponse?: () => void)
new HTTPSClientRequest(onresponse: () => void)

Parameters

ParameterTypeDefaultDescription
opts?HTTPSClientRequestOptionsbare-http1 client request options; agent defaults to HTTPSAgent.global, or pass agent: false to use a fresh HTTPSAgent.
onresponse?() => voidAdded as a one-time 'response' listener.

HTTPSClientRequest._destroy(err: Error | null, cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
errError | null
cbStreamCallback

HTTPSClientRequest._final(cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
cbStreamCallback

HTTPSClientRequest._open(cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
cbStreamCallback

HTTPSClientRequest._predestroy(): void

HTTPSClientRequest._write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
dataunknown
encodingStreamEncoding
cbStreamCallback

HTTPSClientRequest._writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
batch{ chunk: unknown; encoding: StreamEncoding }[]
cbStreamCallback

abort(): void

Destroys the request. An alias of destroy(), for Node.js compatibility.

appendHeader(name: string, value: HTTPHeaderValue): void

Adds value to header name (case-insensitive), keeping any value already set rather than replacing it, so that the field is sent once per value. Cookie is the exception, whose values are folded onto a single line separated by '; '.

Parameters

ParameterTypeDefaultDescription
namestringThe header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__.
valueHTTPHeaderValueThe header value; must not contain a control character other than tab. Every element of an array value is checked in turn, and null is allowed.

Throws

  • HEADERS_SENT — the headers have already been sent.
  • INVALID_HEADER_NAMEname is not a valid RFC 9110 token, or is __proto__.
  • INVALID_HEADER_VALUEvalue is undefined, or contains a control character other than tab.

HTTPSClientRequest.closed: boolean

HTTPSClientRequest.cork(): void

HTTPSClientRequest.destroy(err?: Error | null): void

Parameters

ParameterTypeDefaultDescription
err?Error | null

HTTPSClientRequest.destroyed: boolean

HTTPSClientRequest.destroying: boolean

HTTPSClientRequest.end(cb?: StreamCallback): this

Overloads:

end(cb?: StreamCallback): this
end(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): this
end(data: unknown, cb?: StreamCallback): this

Parameters

ParameterTypeDefaultDescription
cb?StreamCallback

HTTPSClientRequest.errored: Error | null

flushHeaders(): void

Sends the headers immediately, if they haven't already been sent, instead of waiting for the first write.

getHeader(name: string): HTTPHeaderValue | undefined

Returns the value of header name (case-insensitive), or undefined if not set.

Parameters

ParameterTypeDefaultDescription
namestringThe header name (case-insensitive).

getHeaders(): Record<string, HTTPHeaderValue>

Returns a shallow copy of all headers set so far.

hasHeader(name: string): boolean

Returns whether header name (case-insensitive) is set.

Parameters

ParameterTypeDefaultDescription
namestringThe header name (case-insensitive).

headers: Record<string, HTTPHeaderValue>

The headers to send with the request, keyed by lowercase name, including an auto-generated host header.

headersSent: boolean

Whether the headers have already been sent.

method: HTTPMethod

The request method. Defaults to 'GET'.

path: string

The request path. Defaults to '/'.

HTTPSClientRequest.readable: boolean

setHeader(name: string, value: HTTPHeaderValue): void

Sets header name (case-insensitive) to value, replacing any value already set and validating both.

Parameters

ParameterTypeDefaultDescription
namestringThe header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__.
valueHTTPHeaderValueThe header value; must not contain a control character other than tab. Every element of an array value is checked in turn, and null is allowed.

Throws

  • HEADERS_SENT — the headers have already been sent.
  • INVALID_HEADER_NAMEname is not a valid RFC 9110 token, or is __proto__.
  • INVALID_HEADER_VALUEvalue is undefined, or contains a control character other than tab.

HTTPSClientRequest.setTimeout(ms: number, ontimeout?: () => void): this

Sets the underlying socket's timeout to ms and, if given, adds ontimeout as a one-time 'timeout' listener.

Parameters

ParameterTypeDefaultDescription
msnumberThe socket timeout in milliseconds.
ontimeout?() => voidAdded as a one-time 'timeout' listener.

socket: TCPSocket | null

The underlying TCPSocket the message is written to, or null until one is assigned.

HTTPSClientRequest.uncork(): void

upgrade: boolean

Whether the connection was upgraded (for example to a WebSocket) after this message.

HTTPSClientRequest.writable: boolean

HTTPSClientRequest.write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean

Overloads:

write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
write(data: unknown, cb?: StreamCallback): boolean

Parameters

ParameterTypeDefaultDescription
dataunknown
encoding?BufferEncoding
cb?StreamCallback

Functions

createServer

createServer(opts?: HTTPSServerOptions, onrequest?: (req: HTTPIncomingMessage, res: HTTPServerResponse) => void): HTTPSServer

Creates an HTTPSServer. If onrequest is given, it's added as a 'request' listener.

Parameters

ParameterTypeDefaultDescription
opts?HTTPSServerOptionsServer options: TLS socket options (for example cert, key) plus bare-http1 server connection options.
onrequest?(req: HTTPIncomingMessage, res: HTTPServerResponse) => voidAdded as a 'request' listener.

request

request(url: URL | string, opts?: HTTPSClientRequestOptions, onresponse?: (res: HTTPIncomingMessage) => void): HTTPSClientRequest

Creates an HTTPSClientRequest to url (a URL or a URL string), using TLS. If onresponse is given, it's added as a one-time 'response' listener. Does not send the request until it's ended.

Parameters

ParameterTypeDefaultDescription
urlURL | stringThe URL to request, as a URL object or a URL string.
opts?HTTPSClientRequestOptionsbare-http1 client request options; agent defaults to globalAgent, or pass agent: false to use a fresh HTTPSAgent.
onresponse?(res: HTTPIncomingMessage) => voidAdded as a one-time 'response' listener.

get

get(url: URL | string, opts?: HTTPSClientRequestOptions, onresponse?: (res: HTTPIncomingMessage) => void): HTTPSClientRequest

Parameters

ParameterTypeDefaultDescription
urlURL | string
opts?HTTPSClientRequestOptions
onresponse?(res: HTTPIncomingMessage) => void

Constants and variables

globalAgent: HTTPSAgent

The default HTTPSAgent used by request() when no agent option is given.

Types

HTTPSSocketEvents

interface HTTPSSocketEvents {
  connect: []
  data: [data: unknown]
  end: []
  readable: []
  piping: [dest: Writable]
  close: []
  error: [err: Error]
  drain: []
  finish: []
  pipe: [src: Readable]
  lookup: [err: Error | null, address: string | null, family: IPFamily | 0, host: string]
  timeout: []
}

The events an HTTPSSocket emits: those of both TLSSocket and TCPSocket.

HTTPSSocketOptions

interface HTTPSSocketOptions {
  isServer?: boolean
  cert?: ArrayBufferView
  key?: ArrayBufferView
  host?: string
  rejectUnauthorized?: boolean
  ca?: ArrayBufferView
  alpnProtocols?: string[]
  eagerOpen?: boolean
  allowHalfOpen?: boolean
  readBufferSize?: number
  lookup?: DNSLookup
  keepAlive?: boolean | number
  keepAliveInitialDelay?: number
  noDelay?: boolean
  port?: number
  timeout?: number
  family?: `IPv${IPFamily}` | IPFamily | 0
  hints?: number
  all?: boolean
}

Options for HTTPSSocket: those of TLSSocket combined with TCPSocket's connection options.

See also

  • Builds on bare-http1, bare-tcp, and bare-tls.
  • Bare modules — the full bare-* catalog.
  • Bare runtime API — the runtime these modules extend.

On this page

Usage
API
HTTPSSocket
HTTPSSocket._destroy(err: Error | null, cb: StreamCallback): void
HTTPSSocket._final(cb: StreamCallback): void
HTTPSSocket._open(cb: StreamCallback): void
HTTPSSocket._predestroy(): void
_read(size: number): void
HTTPSSocket._write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void
HTTPSSocket._writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void
address(): TCPSocketAddress | null
alpnProtocol: string | null
HTTPSSocket.closed: boolean
connect
connecting: boolean
HTTPSSocket.cork(): void
HTTPSSocket.destroy(err?: Error | null): void
HTTPSSocket.destroyed: boolean
HTTPSSocket.destroying: boolean
encrypted: true
HTTPSSocket.end(cb?: StreamCallback): this
HTTPSSocket.errored: Error | null
HTTPSSocket.keepAlive: boolean
keepAliveInitialDelay: number
localAddress: string
localFamily: string
localPort: number
noDelay: boolean
open(fd: number, opts?: TCPSocketOpenOptions, onconnect?: () => void): this
pause(): this
pending: boolean
pipe<S extends Writable>(dest: S, cb?: StreamCallback): S
push(data: unknown | null, encoding?: BufferEncoding): boolean
read(): unknown | null
HTTPSSocket.readable: boolean
readyState: 'open' | 'opening' | 'readOnly' | 'writeOnly' | 'closed'
ref(): this
remoteAddress: string
remoteFamily: string
remotePort: number
resume(): this
setEncoding(encoding: BufferEncoding): void
setKeepAlive(enable?: boolean, delay?: number): this
setNoDelay(enable?: boolean): this
HTTPSSocket.setTimeout(ms: number, ontimeout?: () => void): this
socket: Duplex
timeout: number
HTTPSSocket.uncork(): void
unref(): this
unshift(data: unknown | null, encoding?: BufferEncoding): boolean
HTTPSSocket.writable: boolean
HTTPSSocket.write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
HTTPSAgent
addRequest(req: HTTPClientRequest, opts: TCPSocketOptions & TCPSocketConnectOptions): void
createConnection(opts?: HTTPSSocketOptions): HTTPSSocket
defaultPort: number
destroy(): void
freeSockets: IterableIterator<TCPSocket>
getName(opts: TCPSocketConnectOptions): string
HTTPSAgent.global: HTTPSAgent
HTTPSAgent.keepAlive: boolean
keepSocketAlive(socket: TCPSocket): boolean
maxFreeSockets: number
maxSockets: number
maxTotalSockets: number
resume(): void
resumed: Promise<void> | null
reuseSocket(socket: TCPSocket, req?: HTTPClientRequest): void
sockets: IterableIterator<TCPSocket>
suspend(): void
suspended: boolean
HTTPSServer
HTTPSServer
HTTPSClientRequest
new HTTPSClientRequest(opts?: HTTPSClientRequestOptions, onresponse?: () => void)
HTTPSClientRequest._destroy(err: Error | null, cb: StreamCallback): void
HTTPSClientRequest._final(cb: StreamCallback): void
HTTPSClientRequest._open(cb: StreamCallback): void
HTTPSClientRequest._predestroy(): void
HTTPSClientRequest._write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void
HTTPSClientRequest._writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void
abort(): void
appendHeader(name: string, value: HTTPHeaderValue): void
HTTPSClientRequest.closed: boolean
HTTPSClientRequest.cork(): void
HTTPSClientRequest.destroy(err?: Error | null): void
HTTPSClientRequest.destroyed: boolean
HTTPSClientRequest.destroying: boolean
HTTPSClientRequest.end(cb?: StreamCallback): this
HTTPSClientRequest.errored: Error | null
flushHeaders(): void
getHeader(name: string): HTTPHeaderValue | undefined
getHeaders(): Record<string, HTTPHeaderValue>
hasHeader(name: string): boolean
headers: Record<string, HTTPHeaderValue>
headersSent: boolean
method: HTTPMethod
path: string
HTTPSClientRequest.readable: boolean
setHeader(name: string, value: HTTPHeaderValue): void
HTTPSClientRequest.setTimeout(ms: number, ontimeout?: () => void): this
socket: TCPSocket | null
HTTPSClientRequest.uncork(): void
upgrade: boolean
HTTPSClientRequest.writable: boolean
HTTPSClientRequest.write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
Functions
createServer
request
get
Constants and variables
globalAgent: HTTPSAgent
Types
HTTPSSocketEvents
HTTPSSocketOptions
See also