Next.js Discord

Discord Forum

Next.js + Python (Flask) WebSocket Security: API Key Exposure Concern

Answered
Sarabi dog posted this in #help-forum
Open in Discord
Avatar
Sarabi dogOP
Hi everyone,

I'm working on Project<X>, a web application that provides nearby beach information. Currently, we've been testing with a simple HTML/JS frontend, but we're planning to migrate to Next.js and Vercel.

Our backend is Flask (running on Docker) with SocketIO for real-time location data in order to calculate nearby distances. My frontend developer raised a concern about API key security in the Next.js implementation.

Specifically, he's saying the API key and backend link would be visible to clients when using Next.js and socketIO.

I'm reaching out to get your expert advice:
- Is this a legitimate concern with Next.js?
- What are the recommended approaches for securing API keys in this architecture?

We want to ensure we're following best practices before moving forward with the implementation.

Looking forward to your insights!
Answered by James4u
browser will be sending the geolocation data with the query at once
View full answer

215 Replies

Avatar
@James4u If you use Next.js only for frontend, your api key will be exposed. As a full stack framework Next.js can be used as BFF.
Avatar
Sarabi dogOP
so u mean if we will use next js api routes the api, backend links will be managed by server side
so the request flow will be like
frontend => Next.js api routes => your python backend
Avatar
Sarabi dogOP
make sense, i wanna convince the same thing to my frontend guy, but somehow he disagree, u will join here shortly
@Nile Crocodile
u can talk now
Avatar
@James4u so the request flow will be like frontend => Next.js api routes => your python backend
Avatar
Nile Crocodile
This what I'm planning to do, but that's not the scenario that @Sarabi dog wants, here is what he wants, a socket link between the frontend and the python backend and the secret api key is on nextjs route is that even possible ???
Avatar
Sarabi dogOP
okay so the fact is, i will give u the backend link which is running on docker
and the api key to get data right?
so whats the issue?
in the backend i have something like this


CORS(app, resources={
r"/api/*": {
"origins": [
"http://127.0.0.1:5500",
"http://localhost:5500",
os.getenv('VERCEL_DOMAIN')
],
"supports_credentials": True,
"methods": ["GET", "POST"],
"allow_headers": [
"Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin"
]
}
})
Avatar
well, @Sarabi dog @Nile Crocodile it's not an issue of Next.js
imagine you are just using React.js for your frontned instead of Next.js
is anything different?
Avatar
Sarabi dogOP
i dont think so, what i can provide is the backend link and the api key to get acess, so whats the issue?
Avatar
so what's API_KEY you guys saying?
Avatar
@James4u so what's API_KEY you guys saying?
Avatar
Sarabi dogOP
in order to make request to the backend to get some json data u need an api key
Avatar
is it something like auth token to protect your python backend?
Avatar
@James4u is it something like auth token to protect your python backend?
Avatar
Sarabi dogOP
yea something like that
Avatar
@James4u huh, then it's always visible
Avatar
Sarabi dogOP
okay but for that we are using nect js api rouets right? which means it will be managed by the server
Avatar
wait wait, is it auth token or API_KEY to use your service
Avatar
Nile Crocodile
I know it's possible that nextjs become the middle man between the frontend and another backend and will work like a proxy there is no issue with that, but that when using regular api calls (http calls get, post .. etc), but but but can it be the middle man if we are using socket call ???????
Avatar
accessToken vs API_KEY which one are you referring to?
nope
Avatar
@James4u wait wait, is it auth token or API_KEY to use your service
Avatar
Sarabi dogOP
using a simple API Key authentication mechanism, not OAuth or a more complex token-based authentication system.
Avatar
it can't be used for web-sockets
Avatar
Nile Crocodile
Yes that's what I'm trying to tell him
Avatar
@Sarabi dog using a simple API Key authentication mechanism, not OAuth or a more complex token-based authentication system.
Avatar
if it's access token that you get after signin - you have to iterate it (meaning your token will be expired in certain amount of time)
and that's what I said, having token public is always fine
just be clear if it's API_KEY or auth token
Avatar
Sarabi dogOP
mmh we didn't implemented signin/sign out yet

cuz i wanna make it accessible for everyone
Avatar
@James4u just be clear if it's API_KEY or auth token
Avatar
Sarabi dogOP
api key
not oauth
so u make request something liek this for testing


curl -X POST https://e9c4-151-72-206-190.ngrok-free.app/api/set_location \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 9xy4QtIe1wkeLvkAbkj9y3C2pIg-nU3SHqG1MPPio_J" \
-d '{
"latitude": 41.9028,
"longitude": 12.4964,
"accuracy": 100,
"location": "naples"
}'
Avatar
will you use HTTP request?
not websocket?
Avatar
Sarabi dogOP
so my architecture supports both:

RESTful HTTP endpoints for standard CRUD operations
WebSocket connections for real-time, event-driven communication
i need socket connection to get real time location data to provide accurate data ..
To illustrate, when a user requests information about nearby beaches, they can navigate from one location to another. In response to this request, the backend sends the request to the frontend via a socket connection, allowing the backend to handle the remaining processing tasks.
Avatar
let's summarize
if you don't have auth in your website, you can't prevent your API_KEY being exposed as long as you use real time connection
Avatar
@James4u if you don't have auth in your website, you can't prevent your API_KEY being exposed as long as you use real time connection
Avatar
Sarabi dogOP
eventhough we are using next js api routes to hide api keys?
i might be wrong cuz i dont have that much exp in this field
what if


1. Move API Key to the Backend
The API key should only reside on the backend, inside a secure environment (like Docker). The frontend communicates with the backend, and the backend then communicates with external services.
Why: This ensures the key is never exposed to the client-side.
Example:

Frontend ➡️ Backend ➡️ External Service (with API Key)
Backend acts as a middleman, keeping the API key secure.
Avatar
well there are 2 problems
then you have to create websocket connection between Next.js api routes and the python server. but Next.js api routes will be deployed as a serverless function that doesn't support long-live connection
let say you deploy your next.js on a server(serverfull not serverless)
but by default your api routes are public
so hitting your api route will create websocket connection, right?
that's why you always need authentication
Avatar
Nile Crocodile
That were my words which been thrown behind their back 😑
Avatar
Sarabi dogOP
mmh so could be the better solution
cuz at the end i dont wanna add oauth like sign in sign out
wanna make it simple so its accessible
for everyone
like perplexity ai
Avatar
so hitting your api route will create websocket connection, right?
then are you okay with ⬆️
however even you are okay with above, you have to leave vercel
next.js api routes deployed on Vercel are serverless
websocket doesn't work on it
you may have to move to fly.io or some other services
Avatar
@James4u `so hitting your api route will create websocket connection, right?`
Avatar
Sarabi dogOP
Yes, based on my existing code and the use of Flask-SocketIO, it's likely that hitting our API route will initiate a WebSocket connection.
Avatar
@James4u `so hitting your api route will create websocket connection, right?`
Avatar
Nile Crocodile
Which is a horrible scenario 😅
Avatar
well my recommendation will be
add some levels to your API_KEY
so for the public access, API_KEY will be only able to use your service 5 times a day or something
and also ADD auth to your system - after login, provide higher API_KEY
Avatar
Sarabi dogOP
for example i have added rate limits, if more than 5 requests per minutes he will get blocked for an hour lets say
Avatar
@James4u and also ADD auth to your system - after login, provide higher API_KEY
Avatar
Sarabi dogOP
so we can't make it secure without user authentication
Avatar
lol authenticated system is not 100% secure
what can we expect from un-authed system in terms of security??
Avatar
Sarabi dogOP
if i will remove the real time location system, and store the location data on a session file for once , then i might not get any issues?
Avatar
@James4u what can we expect from un-authed system in terms of security??
Avatar
Sarabi dogOP
tough question
cuz at the end u are handling it
what kind of data do you want to show in the real time?
Avatar
@James4u what kind of data do you want to show in the real time?
Avatar
Sarabi dogOP
okay so lets say u asked to our Ai what are some beaches nearby, the backend will send a request to the frontend to get the realtime user coordinates
send back to the backend to proces for the rest
Avatar
I feel like what you are saying is more close to streaming AI
Avatar
Nile Crocodile
Replace the socket with regular https request, you assuming it's real-time but it's not, because we are giving the user the data after he request it so why don't we use regular http calls.

Then the full scenario well be like this, the user call a route or a server action in next then next call the python backend secure and simple.
Avatar
sorry I think I misunderstood your meaning
so what's real time user coordinates?
user geolocation?
Avatar
@James4u I feel like what you are saying is more close to streaming AI
Avatar
Nile Crocodile
It's not it's been delivered to you like that but it's not.
Avatar
@James4u user geolocation?
Avatar
Sarabi dogOP
yess
Avatar
oh, how can he move fast to get different results from the server while server is preparing something for the user
or am I silly to miss something? 🤣
Avatar
@James4u oh, how can he move fast to get different results from the server while server is preparing something for the user
Avatar
Sarabi dogOP
lets say right now u are in ur home to get nearby beaches

once u go there u ask what are some restaurants nearby
in that case we need ur geolocation data
Avatar
yes?
Avatar
Nile Crocodile
Lol it's chat website that needs your location data to make some calculation.
Avatar
@Nile Crocodile Lol it's chat website that needs your location data to make some calculation.
Avatar
Sarabi dogOP
yes but it depends on ur position
if u are at home and then moved to some place, if u ask about nearby places, u will not get accurate data
Avatar
no no my point is that
Avatar
Nile Crocodile
You simple ask it and it will answers, it will never provide data if you didn't make a request to it, what is the need for socket here ?
Avatar
why don't you get user's location when they request something?
Avatar
@James4u why don't you get user's location when they request something?
Avatar
Sarabi dogOP
yes, i did this configuration
but somehoe u guys are saying that api will be visible
so only if u request
Avatar
well, I think you misunderstood
Avatar
@Nile Crocodile Lol it's chat website that needs your location data to make some calculation.
Avatar
Sarabi dogOP
at the end u will see a small ai model instead of the api
Avatar
Nile Crocodile
You are mixing the points
Avatar
yeah mixing two points
they are independant things
Avatar
Sarabi dogOP
okay tell me what i am missing
Avatar
so let me adjust the flow
Avatar
Sarabi dogOP
ok
Avatar
user ask your AI bot - "what are the nearest shops?"
frontend hits your next.js api route
you can get his location - you don't need to make another request again to get user location
this step is where you are missing
Avatar
@James4u you can get his location - you don't need to make another request again to get user location
Avatar
Sarabi dogOP
u got his location by requesting to the frontend?
user ask a question and we obivously send this question to the server (in this case Next.js api route)
right?
Avatar
Sarabi dogOP
yes
Avatar
@Sarabi dog u got his location by requesting to the frontend?
Avatar
request is something from client/browser to the server/api route
Avatar
Sarabi dogOP
so to process the data backend needs geolocation data, right<'
Avatar
@Sarabi dog so to process the data backend needs geolocation data, right<'
Avatar
Sarabi dogOP
my point is how it will get from
Avatar
in previous next.js versions, you were able to get gelocation info from request param of the api route
but they moved that stuff recently thinking it's more like vercel feature that they don't normally need
check this npm @vercel/functions
Avatar
Sarabi dogOP
so for each request we are making a geolocation request as backend needs right?
Avatar
yeah, exactly
Avatar
Sarabi dogOP
right now the project is structured like this

@Nile Crocodile so what i did wrong
Avatar
I am not sure how this npm works behind but what I can sure is that it's not making a request to the browser like your scenario
Avatar
@James4u I am not sure how this npm works behind but what I can sure is that it's not making a request to the browser like your scenario
Avatar
Sarabi dogOP
so instead of making the request to the browser(client) where it makes request?
Avatar
@Sarabi dog so instead of making the request to the browser(client) where it makes request?
Avatar
am not sure if it's actually making a request - but yeah it must be
maybe to vercel service?
does it matter?
Avatar
Nile Crocodile
Nooooo
It doesn't matter
Avatar
@Nile Crocodile Nooooo
Avatar
Sarabi dogOP
??
Avatar
@Nile Crocodile It doesn't matter
Avatar
Sarabi dogOP
so whats ur solution, and what u want me to change
Avatar
okay as I research, this npm doesn't make any request to third parties as long as you deploy your Next.js on Vercel
but if you don't deploy your project on Vercel you are not able to use this api
Avatar
@James4u but if you don't deploy your project on Vercel you are not able to use this api
Avatar
Sarabi dogOP
are there rate limits for this api?
Avatar
@Sarabi dog so whats ur solution, and what u want me to change
Avatar
well, what you have to change is to update your python server to get user query and location at once
and preocess send the response
Avatar
@Sarabi dog are there rate limits for this api?
Avatar
no no totally not usable
you need to use alternative ways to get geolocation data from the http request data
Avatar
@James4u and preocess send the response
Avatar
Sarabi dogOP
i believe right now its structured like this
Avatar
Nile Crocodile
The user location will be accessed through the browser, the frontend developer with take this data and put to the request that is going to next route, the route will take the data and make a request to python server with the data, python will respond to next route then the route will deliver the results to the client
Simple as that
Avatar
@Sarabi dog i believe right now its structured like this
Avatar
you said server is making request to the browser to get user's geolocation
Avatar
@James4u you said server is making request to the browser to get user's geolocation
Avatar
Sarabi dogOP
yes cuz i am using socketIO for that
Avatar
from browser? what if user declines?
Avatar
@James4u from browser? what if user declines?
Avatar
Sarabi dogOP
they can't access to our platform
Avatar
@James4u not at all I think
Avatar
Nile Crocodile
The browser has gps in it or not ?
Avatar
Sarabi dogOP
to use our ai chatbot
Avatar
@Nile Crocodile The browser has gps in it or not ?
Avatar
Sarabi dogOP
it asks u to give permission
Avatar
Nile Crocodile
I mean a gps api
Avatar
okay that makes sense
Avatar
Nile Crocodile
The gps is on the device
Avatar
Sarabi dogOP
so here's the point, instead of making request to the browser where should i send the request
Avatar
you don't need to make any request
Avatar
@James4u you don't need to make any request
Avatar
Sarabi dogOP
u are getting all at once?
Avatar
browser will be sending the geolocation data with the query at once
Answer
Avatar
@James4u browser will be sending the geolocation data with the query at once
Avatar
Sarabi dogOP
okay, what if he moves to another place after an hour, will the geo data be same or different
Avatar
if he starts a new query, browser will be sending the new geolocation
Avatar
@James4u if he starts a new query, browser will be sending the new geolocation
Avatar
Sarabi dogOP
right now it works like this but uses socket
tell me if i am wrong @Nile Crocodile
Avatar
Nile Crocodile
No need for socket
Avatar
Sarabi dogOP
ok instead of socket what to modify
thats where i got stuck
Avatar
to clarify websocket is when you want to get real time events from the server
here what can be changing by time is user location on the client side
does this make sense to you all?
if something has been changed on the client side, you just make a request to the server again with updated info
but server can't send a request to the browser - that's why we need websockets
Avatar
is everything clear now guys?
🙂
Avatar
Sarabi dogOP
yes, but for other cases such as

if u reload the page it will trigger to the backend to take a certain action through an api endpoint

instead of socket how can i handle it
Avatar
hmm didn't follow you - can you tell me your problem exactly?
not initially but only if u reload the page
Avatar
it's not related to the websocket I believe
Avatar
@Sarabi dog not initially but only if u reload the page
Avatar
hit the backend everytime you refresh the page
what's the problem? we have useEffect(() => {}, []);
right?
Avatar
Sarabi dogOP
yes
Avatar
Nile Crocodile
@Sarabi dog are you trying to clear the session?
Avatar
Sarabi dogOP
yes,
only the chat history
Avatar
oh please don't ask to ask
gimme the problem @Sarabi dog @Nile Crocodile 😞
it keeps our conv long and long
Avatar
Sarabi dogOP
can we talk?
if possible
Avatar
just tell me
Avatar
@Sarabi dog yes,
Avatar
Nile Crocodile
What if his network connection lost ??
Avatar
@Nile Crocodile What if his network connection lost ??
Avatar
Sarabi dogOP
it will not trigger
it will only trigger if u reload while having connection
here in europe i dont think we will have network issues
Avatar
just tell me the UX feature you want to build/improve
Avatar
@James4u just tell me the UX feature you want to build/improve
Avatar
Sarabi dogOP
@Nile Crocodile
do u want me to provide api endpoint details?
Avatar
thinking following questions are out of the original question and more related to your internal coversation
@Sarabi dog can you close this thread by marking a solution?
Avatar
Sarabi dogOP
alright
thanks a lot
Avatar
yr welcome