Skip to content

API Gateway implemented with Node and Express

This project implements a proxy server using Express and http-proxy-middleware to forward requests to backend services. Additionally, it uses JWTs (JSON Web Tokens) to authenticate and authorize requests.

Project Structure

  • app.ts: Main file that configures the Express server, JWT authentication middleware, and proxy logic.
  • index.ts: Application entry point that starts the server.
  • app.spec.ts: Test file using supertest and jest to verify the proxy and authentication behavior.

Features

  1. JWT Authentication: The middleware checks if a valid JWT is provided in the Authorization header. If the token is invalid or missing, the request is blocked.

  2. Proxy Middleware: Requests to the /users path are forwarded to the user management service. During the proxy, the x-user header is added, containing information extracted from the JWT.

  3. Automated Tests: The project includes tests to verify authentication and proxy behavior.

Configuration

Environment Variables

  • SECRET_KEY: Secret key to sign and verify JWTs. It must be defined in the .env file.
  • USER_MANAGEMENT_API: URL of the user management service.
  • PORT: Port on which the Express server will run.

Starting the Server

  1. Install dependencies with npm install.
  2. Run the server with npm start.

Testing

Tests are performed using jest and supertest. To run the tests, use:

npm test

Usage Examples

Request with a Valid JWT

curl -H "Authorization: Bearer <valid_jwt_token>" http://localhost:<PORT>/users

Request without a JWT

curl http://localhost:<PORT>/users

Note: A request without a valid JWT will return a 403 or 401 error.

Adding New Endpoints

To add new endpoints, follow these steps:

  1. Define the middleware: Use the existing JWT middleware to protect new routes, or create a new one if necessary.

  2. Configure the Proxy: Use createProxyMiddleware to define new proxy rules. Example:

    app.use('/new-endpoint', createProxyMiddleware({
        target: 'http://new-service:8080',
        changeOrigin: true,
        on: proxyEvents,
        logger: console
    }));
    
  3. Test the Endpoint: Create tests using supertest in the app.spec.ts file to verify the behavior.

TDD Test Example

To create a TDD-based test, follow this example:

it('should return 404 for a non-existent route', async () => {
    const response = await request(app).get('/non-existent-route');
    expect(response.status).toBe(404);
});

Glossary

  • JWT (JSON Web Token): An open standard token that allows for the secure transmission of information between parties as a JSON object.
  • Middleware: Functions that have access to the request object (req), the response object (res), and the next middleware function in the request-response cycle.
  • Proxy: An intermediary for client requests seeking resources from other servers.
  • Express: A framework for Node.js that provides a robust set of features for web and mobile applications.
  • http-proxy-middleware: A middleware for Node.js that acts as a reverse proxy, routing requests to different servers.
  • supertest: A library for testing HTTP applications using Node.js.
  • dotenv: A module that loads environment variables from a .env file into process.env.