Build an Api Proxy Server

Api proxy

A proxy is something sitting between the application and backend or some third party services. we can benifit from a proxy in many places

  • Translate request formats
  • Avoid expose the token, key etc. for the integration with some third party sevices
  • Perform data transformation

Build an Api proxy server

  • Install packages
npm i express dotenv cors needle
npm i -D nodemon
npm i express-rate-limit apicache
const url = require('url')
const express = require('express')
const router = express.Router()
const needle = require('needle')
const apicache = require('apicache')

const API_BASE_URL = process.env.API_BASE_URL
const API_KEY_NAME = process.env.API_KEY_NAME
const API_KEY_VALUE = process.env.API_KEY_VALUE

let cache = apicache.middleware

router.get('/',cache('2 minutes'),async (req, res) => {
    try {
       // console.log(url.parse(req.url, true).query)
        const params = new URLSearchParams({
            [API_KEY_NAME]: API_KEY_VALUE,
            ...url.parse(req.url, true).query,
        })

        if (process.env.NODE_ENV !== 'production')
        {
            console.log({
                [API_KEY_NAME]: API_KEY_VALUE,
                ...url.parse(req.url, true).query,
            })
            console.log(`REQUEST: ${API_BASE_URL}?${params}`)
        }
        
        const apiRes = await needle('get',`${API_BASE_URL}?${params}`)
        const data = apiRes.body
        res.status(200).json(data)    
    }
    catch (error)
    {
        res.status(500).json({error})
    }
})
module.exports = router
  • Main js with rate limit
const express = require('express')
const cors = require('cors')
const rateLimit = require('express-rate-limit')

require('dotenv').config()

const PORT = process.env.PORT || 5000

const app = express()

//rate limiting
const limiter = rateLimit({
    windowMs: 10 * 60 * 1000, //10 Mins
    max: 500,
})
app.use(limiter)
app.set('trust proxy', 1)

app.use(express.static('public'))

//Routes
app.use('/api',require('./routes'))

app.use(cors())

app.listen(PORT, () => console.log(`Server running on port ${PORT}`))

Reference