How to handle authentication for API requests from different sources

I built a sports data API that users can access directly from my website. Each user gets limited requests and needs an API key for authentication. Now I also put my API on RapidAPI marketplace where users get different API keys from RapidAPI itself.

The problem is that RapidAPI validates their keys before sending requests to my server, but I need to figure out how to handle authentication properly. When requests come directly to my website, I should check the API key myself. When they come through RapidAPI, I should skip my own validation since RapidAPI already did it.

Here’s what I’m trying to achieve in my Express route:

app.get('/api/:category/data', async (request, response) => {
    // detect if request originated from RapidAPI platform and skip validation
    
    // for direct requests, verify the user_token from query params before proceeding
})

What’s the best way to distinguish between these two types of requests and handle authentication accordingly?

I ran into this exact issue with multiple API gateways. Don’t just rely on headers - set up a config-based system with trusted sources in your environment variables. Build middleware that checks both headers and IP addresses against your whitelist. RapidAPI sends an X-RapidAPI-Version header that’s tougher to spoof, so use that too. Here’s what tripped me up: error handling needs to be different for each source. RapidAPI wants specific status codes for their analytics, but your direct users need different error formats. I built separate response handlers based on request source. And definitely log these requests separately - you’ll go crazy troubleshooting if you can’t tell which source caused the problem.

create a middleware that checks the user-agent string - rapidapi has a distinct pattern. I’ve seen people get burned by only checking headers, so combine it with request origin validation. also handle the edge case where someone hits your api directly but spoofs the rapidapi headers. you’ll want to fail gracefully instead of breaking everything.

RapidAPI sends specific headers you can use to identify their requests. Look for X-RapidAPI-Host (your API’s hostname on their platform) and X-RapidAPI-Key (the user’s subscription key). I built dual auth with middleware that checks for these headers first. If they’re there, I flag it as RapidAPI and skip internal validation. If not, it goes through normal API key checks. Watch out though - these headers can be spoofed. Consider whitelisting RapidAPI’s IP ranges or adding extra verification. Also set up separate rate limits since RapidAPI users probably have different quotas than direct users.