• Creates a middleware, that checks for an API key.

    Parameters

    Returns UniqueHttpMiddleware

    The new middleware.

    Example

    import assert from 'assert'
    import createServer, { ApiKeyValidator, HttpRequestHandler, IHttpRequest, IHttpResponse, apiKey } from '@egomobile/http-server'

    // custom validator function
    const myApiKeyValidator: ApiKeyValidator =
    async (request: IHttpRequest) => request.headers['x-key'] === 'mySecretApiKey3'

    // custom error handler
    const onValidationFailed: HttpRequestHandler = async (request: IHttpRequest, response: IHttpResponse) => {
    const errorMessage = Buffer.from('Wrong API key!', 'utf8')

    response.writeHead(403, {
    'Content-Length': String(errorMessage.length)
    });

    response.write(errorMessage)
    }

    const app = createServer()

    // check 'x-api-key' header for 'mySecretApiKey1'
    app.get('/foo', [apiKey('mySecretApiKey1')], async (request: IHttpRequest, response: IHttpResponse) => {
    assert.strictEqual(request.headers['x-api-key'], 'mySecretApiKey1')
    })

    // check 'x-key' header for 'mySecretApiKey2'
    app.get('/bar', [apiKey('mySecretApiKey2', 'x-key')], async (request: IHttpRequest, response: IHttpResponse) => {
    assert.strictEqual(request.headers['x-key'], 'mySecretApiKey2')
    })

    // use function to validate
    app.get('/baz', [apiKey(myApiKeyValidator)], async (request: IHttpRequest, response: IHttpResponse) => {
    assert.strictEqual(request.headers['x-key'], 'mySecretApiKey3')
    })

    // with custom error handler
    app.get('/test', [apiKey(myApiKeyValidator, onValidationFailed)], async (request: IHttpRequest, response: IHttpResponse) => {
    assert.strictEqual(request.headers['x-key'], 'mySecretApiKey3')
    })
  • Parameters

    Returns UniqueHttpMiddleware

  • Parameters

    • key: string

    Returns UniqueHttpMiddleware

  • Parameters

    • key: string
    • header: string

    Returns UniqueHttpMiddleware

  • Parameters

    Returns UniqueHttpMiddleware

  • Parameters

    Returns UniqueHttpMiddleware

Generated using TypeDoc