Class HttpRequestContext<Context>

Type Parameters

  • Context extends Record<any, any> = {}

Hierarchy

Constructors

Properties

$status: Readonly<{
    ACCEPTED: 202;
    ALREADY_REPORTED: 208;
    BAD_GATEWAY: 502;
    BAD_REQUEST: 400;
    BANDWIDTH_LIMIT_EXCEEDED: 509;
    CONFLICT: 409;
    CONTINUE: 100;
    CREATED: 201;
    EARLY_HINTS: 103;
    EXPECTATION_FAILED: 417;
    FAILED_DEPENDENCY: 424;
    FORBIDDEN: 403;
    FOUND: 302;
    GATEWAY_TIMEOUT: 504;
    GONE: 410;
    HTTP_VERSION_NOT_SUPPORTED: 505;
    IM_A_TEAPOT: 418;
    IM_USED: 226;
    INSUFFICIENT_STORAGE: 507;
    INTERNAL_SERVER_ERROR: 500;
    LENGTH_REQUIRED: 411;
    LOCKED: 423;
    LOOP_DETECTED: 508;
    METHOD_NOT_ALLOWED: 405;
    MISDIRECTED_REQUEST: 421;
    MOVED_PERMANENTLY: 301;
    MULTIPLE_CHOICES: 300;
    MULTI_STATUS: 207;
    NETWORK_AUTHENTICATION_REQUIRED: 511;
    NON_AUTHORATIVE_INFORMATION: 203;
    NOT_ACCEPTABLE: 406;
    NOT_EXTENDED: 510;
    NOT_FOUND: 404;
    NOT_IMPLEMENTED: 501;
    NOT_MODIFIED: 304;
    NO_CONTENT: 204;
    OK: 200;
    PARTIAL_CONTENT: 206;
    PAYLOAD_TOO_LARGE: 413;
    PAYMENT_REQUIRED: 402;
    PERMANENT_REDIRECT: 308;
    PRECONDITION_FAILED: 412;
    PRECONDITION_REQUIRED: 428;
    PROCESSING: 102;
    PROXY_AUTHENTICATION_REQUIRED: 407;
    RANGE_NOT_SATISFIABLE: 416;
    REQUEST_HEADER_FIELDS_TOO_LARGE: 431;
    REQUEST_TIMEOUT: 408;
    RESET_CONTENT: 205;
    SEE_OTHER: 303;
    SERVICE_UNAVAILABLE: 503;
    SWITCHING_PROTOCOLS: 101;
    TEMPORARY_REDIRECT: 307;
    TOO_EARLY: 425;
    TOO_MANY_REQUESTS: 429;
    UNAUTHORIZED: 401;
    UNAVAILABLE_FOR_LEGAL_REASONS: 451;
    UNPROCESSABLE_ENTITY: 422;
    UNSUPPORTED_MEDIA_TYPE: 415;
    UPGRADE_REQUIRED: 426;
    URI_TOO_LONG: 414;
    USE_PROXY: 305;
    VARIANT_ALSO_NEGOTIATES: 506;
}> = status

HTTP Status Codes Enum

Type declaration

  • ACCEPTED: 202
  • ALREADY_REPORTED: 208
  • BAD_GATEWAY: 502
  • BAD_REQUEST: 400
  • BANDWIDTH_LIMIT_EXCEEDED: 509
  • CONFLICT: 409
  • CONTINUE: 100
  • CREATED: 201
  • EARLY_HINTS: 103
  • EXPECTATION_FAILED: 417
  • FAILED_DEPENDENCY: 424
  • FORBIDDEN: 403
  • FOUND: 302
  • GATEWAY_TIMEOUT: 504
  • GONE: 410
  • HTTP_VERSION_NOT_SUPPORTED: 505
  • IM_A_TEAPOT: 418
  • IM_USED: 226
  • INSUFFICIENT_STORAGE: 507
  • INTERNAL_SERVER_ERROR: 500
  • LENGTH_REQUIRED: 411
  • LOCKED: 423
  • LOOP_DETECTED: 508
  • METHOD_NOT_ALLOWED: 405
  • MISDIRECTED_REQUEST: 421
  • MOVED_PERMANENTLY: 301
  • MULTIPLE_CHOICES: 300
  • MULTI_STATUS: 207
  • NETWORK_AUTHENTICATION_REQUIRED: 511
  • NON_AUTHORATIVE_INFORMATION: 203
  • NOT_ACCEPTABLE: 406
  • NOT_EXTENDED: 510
  • NOT_FOUND: 404
  • NOT_IMPLEMENTED: 501
  • NOT_MODIFIED: 304
  • NO_CONTENT: 204
  • OK: 200
  • PARTIAL_CONTENT: 206
  • PAYLOAD_TOO_LARGE: 413
  • PAYMENT_REQUIRED: 402
  • PERMANENT_REDIRECT: 308
  • PRECONDITION_FAILED: 412
  • PRECONDITION_REQUIRED: 428
  • PROCESSING: 102
  • PROXY_AUTHENTICATION_REQUIRED: 407
  • RANGE_NOT_SATISFIABLE: 416
  • REQUEST_HEADER_FIELDS_TOO_LARGE: 431
  • REQUEST_TIMEOUT: 408
  • RESET_CONTENT: 205
  • SEE_OTHER: 303
  • SERVICE_UNAVAILABLE: 503
  • SWITCHING_PROTOCOLS: 101
  • TEMPORARY_REDIRECT: 307
  • TOO_EARLY: 425
  • TOO_MANY_REQUESTS: 429
  • UNAUTHORIZED: 401
  • UNAVAILABLE_FOR_LEGAL_REASONS: 451
  • UNPROCESSABLE_ENTITY: 422
  • UNSUPPORTED_MEDIA_TYPE: 415
  • UPGRADE_REQUIRED: 426
  • URI_TOO_LONG: 414
  • USE_PROXY: 305
  • VARIANT_ALSO_NEGOTIATES: 506

Since

9.0.0

@: Context = ...

Context Variables that are available anywhere in the requests lifespan

Since

1.2.1

abort: AbortSignal
client: {
    internal: boolean;
    ip: IPAddress<4 | 6>;
    origin: string;
    port: number;
    proxied: boolean;
    referrer: string;
    userAgent: string;
}

Client Infos

Type declaration

  • Readonly internal: boolean

    Whether the Client IP Address is from an internal fetch

    Since

    9.3.0

  • Readonly ip: IPAddress<4 | 6>

    The IP Address that the Client is using

    When a valid Proxy Request is made (and proxy is enabled) this will be the proper IP

    Since

    3.0.0

  • Readonly origin: string

    The Origin of the Clients Request

    Since

    9.5.0

    Example

    localhost:8000
    
  • Readonly port: number

    The Port that the Client is using

    Since

    3.0.0

  • Readonly proxied: boolean

    Whether the Client IP Address is proxied

    Since

    9.3.0

  • Readonly referrer: string

    The Referrer of the Clients Request

    Since

    9.5.0

    Example

    https://localhost:8000/me
    
  • Readonly userAgent: string

    The User Agent of the Client

    Since

    3.0.0

context: RequestContext<any>

The Request Context Object used by the server

Since

9.0.0

The Global Context Object used by the server

Since

9.0.0

headers: ValueCollection<string, string, Content>

A Collection of all Headers

Example

if (ctr.headers.has('authorization')) console.log('Authorization Header is present')

console.log(ctr.headers.get('authorization')) // Will print undefined if not present
console.log(ctr.headers.get('authorization', 'hello')) // Will print 'hello' if not present

Since

2.0.0

params: BaseCollection<string, string>

A Collection of all Path Parameters

Example

console.log(ctr.params.get('server')) // Will print undefined if not present

Since

2.0.0

server: Server<{}, [], {}>

The Server Object that initialized this Request

Type declaration

    Type declaration

      Since

      9.8.0

      type: "http" | "ws"

      The Type of this Request

      Since

      5.7.0

      url: default

      The Requested URL

      Since

      0.0.2

      Accessors

      • get cookies(): ValueCollection<string, string, Cookie>
      • A Collection of all Client Cookies

        Returns ValueCollection<string, string, Cookie>

        Example

        import { Cookie } from "rjweb-server"

        if (ctr.cookies.has('theme')) console.log('Theme Cookie is present')

        console.log(ctr.cookies.get('theme')) // Will print undefined if not present
        console.log(ctr.cookies.get('theme', 'light')) // Will print 'light' if not present

        ctr.cookies.set('session', new Cookie(Math.random(), {
        path: '/'
        }))

        Since

        2.0.0

      • get fragments(): BaseCollection<string, string>
      • A Collection of all URL Fragments

        Returns BaseCollection<string, string>

        Example

        if (ctr.fragments.has('user')) console.log('User Fragment is present')

        console.log(ctr.fragments.get('user')) // Will print undefined if not present
        console.log(ctr.fragments.get('user', 'default')) // Will print 'default' if not present

        Since

        7.0.0

      • get queries(): BaseCollection<string, string>
      • A Collection of all URL Queries

        Returns BaseCollection<string, string>

        Example

        if (ctr.queries.has('user')) console.log('User Query is present')

        console.log(ctr.queries.get('user')) // Will print undefined if not present
        console.log(ctr.queries.get('user', 'default')) // Will print 'default' if not present

        Since

        2.0.0

      Methods

      • HTTP Abort Controller (please use to decrease server load)

        Parameters

        • Optional callback: (() => void)
            • (): void
            • Returns void

        Returns boolean

        Since

        9.0.0

      • Grab a Channel from either a string identifier or a Channel object

        Type Parameters

        Parameters

        Returns Channel<C>

        Example

        const channel = ctr.$channel('channel')

        await channel.send('text', 'Ok')

        // or

        const ref = new Channel<string>()
        const channel = ctr.$channel(ref)

        await channel.send('text', 'Ok')

        Since

        9.8.0

      • Bind the Body using Zod

        This uses .body internally so no binary data

        Type Parameters

        • Schema extends ZodTypeAny

        Parameters

        Returns Promise<ZodResponse<Schema>>

        Example

        const [ data, error ] = await ctr.bindBody((z) => z.object({
        name: z.string().max(24),
        gender: z.union([ z.literal('male'), z.literal('female') ])
        }))

        if (!data) return ctr.status(ctr.$status.BAD_REQUEST).print(error.toString())

        ctr.print('Everything valid! 👍')
        ctr.printPart(`
        your name is ${data.name}
        and you are a ${data.gender}
        `)

        Since

        8.8.0

      • Clear the active Ratelimit of the Client

        This Clears the currently active Ratelimit (on this endpoint) of the Client, remember: you cant call this in a normal endpoint if the max hits are already reached since well... they are already reached.

        Returns this

        Since

        8.6.0

      • Print a Message to the Client (automatically Formatted)

        This Message will be the one actually sent to the client, nothing can be "added" to the content using this function, it can only be replaced using .print() To add content to the response body, use .printPart() instead.

        Parameters

        • content: Content
        • prettify: boolean = false

        Returns this

        Example

        ctr.print({
        message: 'this is json!'
        })

        // content will be `{"message":"this is json!"}`

        /// or

        ctr.print({
        message: 'this is json!'
        }, true)
        // content will be `{\n "message": "this is json!"\n}`

        /// or

        ctr.print('this is text!')
        // content will be `this is text!`

        Since

        0.0.2

      • Print a Message to the client (without resetting the previous message state)

        This will turn your response into a chunked response, this means that you cannot add headers or cookies after this function has been called. This function is useful if you want to add content to the response body without resetting the previous content. And when you manually want to print massive amounts of data to the client without having to store it in memory.

        Type Parameters

        • Callback extends null | ((print) => Promise<any>)

        Parameters

        Returns Callback extends null
            ? Writable
            : HttpRequestContext<Context>

        Example

        const file = fs.createReadStream('./10GB.bin')

        ctr.printChunked((print) => new Promise<void>((end) => {
        file.on('data', (chunk) => {
        file.pause()
        print(chunk)
        .then(() => file.resume())
        })

        file.on('end', () => {
        end()
        })

        ctr.$abort(() => {
        file.destroy()
        end()
        })
        }))

        Since

        8.2.0

      • Print the Content of a File to the Client

        This will print a file to the client using transfer encoding chunked and if addTypes is enabled automatically add some content types based on the file extension. This function wont respect any other http response body set by .print() or any other normal print as this overwrites the custom ctx execution function.

        Parameters

        • file: string
        • options: {
              addTypes?: boolean;
              compress?: boolean;
              download?: boolean;
              name?: string;
          } = {}
          • Optional addTypes?: boolean

            Whether some Content Type Headers will be added automatically

            Default

            true
            

            Since

            2.2.0

          • Optional compress?: boolean

            Whether to compress this File

            Default

            true
            

            Since

            7.9.0

          • Optional download?: boolean

            Whether to download the file or display it in the browser

            Default

            ctr.context.response.headers.get('content-type') === 'application/octet-stream'
            

            Since

            9.1.4

          • Optional name?: string

            The Name of the File (if not set, the basename of the file will be used)

            Only applied if the content-disposition header is not set and options.download is true

            Default

            path.basename(file)
            

            Since

            9.1.4

        Returns this

        Example

        ctr.printFile('./profile.png', {
        addTypes: true // Automatically add Content types
        })

        Since

        0.6.3

      • Redirect a Client to another URL

        This will set the location header and the status to either to 301 or 302 depending on whether the server should tell the browser that the page has permanently moved or temporarily. Obviously this will only work correctly if the client supports the 30x Statuses combined with the location header.

        Parameters

        • location: string
        • type: "temporary" | "permanent" = 'temporary'

        Returns this

        Example

        ctr.redirect('https://example.com', 'permanent') // Will redirect to that URL
        

        Since

        2.8.5

      • Skips counting the request to the Client IPs Rate limit (if there is one)

        When a specific IP makes a request to an endpoint under a ratelimit, the maxhits will be increased instantly to prevent bypassing the rate limit by spamming requests faster than the host can handle. When this function is called, the server removes the set hit again.

        Returns this

        Since

        8.6.0

      • The Request Status to Send

        This will set the status of the request that the client will recieve, by default the status will be 200, the server will not change this value unless calling the .redirect() method. If you want to add a custom message to the status you can provide a second argument that sets that, for RFC documented codes this will automatically be set but can be overridden, the mapping is provided by http.STATUS_CODES

        Parameters

        • code: number
        • Optional message: string

        Returns this

        Example

        ctr.status(401).print('Unauthorized')

        // or
        ctr.status(666, 'The Devil').print('The Devil')

        // or
        ctr.status(ctr.$status.IM_A_TEAPOT).print('Im a Teapot, mate!')

        Since

        0.0.2

      • Add a Header the response depended on (vary header)

        This will add a header to the response that tells the client that the response is dependent on the value of the header, this is useful if you want to cache responses that are dependent on the value of a header.

        Parameters

        • header: string

        Returns this

        Example

        switch (ctr.client.origin) {
        case "localhost": {
        return ctr.vary('origin').print('Hi, ur cool')
        }

        default: {
        return ctr.vary('origin').print('You are gay.')
        }
        }

        Since

        9.3.4

        See

        https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary

      • HTTP WWW-Authentication Checker

        This will validate the Authorization Header using the WWW-Authentication Standard, you can choose between basic and digest authentication, in most cases digest should be used unless you are using an outdated client or want to test easily. When not matching any user the method will return null and the request should be ended with a Status.UNAUTHORIZED (401) status code.

        Type Parameters

        • Users extends Record<string, string>

        Parameters

        • type: "basic" | "digest"
        • reason: string
        • users: Users

        Returns null | keyof Users

        Example

        const user = ctr.wwwAuth('basic', 'Access this Page.', { // Automatically adds www-authenticate header
        bob: '123!',
        rotvproHD: 'password'
        })

        if (!user) return ctr.status(ctr.$status.UNAUTHORIZED).print('Invalid credentials')

        ctr.print(`You authenticated with user: ${user}`)

        Since

        8.0.0

      • Yield the Request to the next Route that matches the URL

        This will yield the request to the next route that matches the URL, this is useful if you want to have multiple routes that match the same URL but have different methods or if you want to have a fallback route that matches all URLs. You can also pass data to the next route by providing it as an argument.

        Type Parameters

        • Data = unknown

        Parameters

        Returns default<Data>

        Example

        const server = new Server(...)

        server.path('/api', (path) => path
        .http('GET', '/', (http) => http
        .onRequest((ctr) => {
        if (ctr.queries.has('yield')) return ctr.yield('Hello World!')

        ctr.headers.set('content-type', 'text/html')
        ctr.print('<a href="/api?yield">yield this shit</a>')
        })
        )
        .http('GET', '/', (http) => http
        .onRequest((ctr) => {
        ctr.print(`u yielded, ${ctr.yield().data()}`) // u yielded, Hello World!
        })
        )
        )

        Since

        9.2.0