Next.js + Python (Flask) WebSocket Security: API Key Exposure Concern
Answered
Sarabi dog posted this in #help-forum
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!
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
215 Replies
@Sarabi dog 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!
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.
As a full stack framework Next.js can be used as BFF.
use Next.js api routes as proxy
@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.
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
frontend => Next.js api routes => your python backend
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
@James4u so the request flow will be like
frontend => Next.js api routes => your python backend
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 ???
@Nile Crocodile This what I'm planning to do, but that's not the scenario that <@711980188543615107> 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 ???
lol - a bit difficult to understand your English but
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"
]
}
})
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"
]
}
})
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?
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?
@Nile Crocodile This what I'm planning to do, but that's not the scenario that <@711980188543615107> 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 ???
Basenji
if you mean the next.js api routes, then its fine
so what's API_KEY you guys saying?
@James4u so what's API_KEY you guys saying?
Sarabi dogOP
in order to make request to the backend to get some json data u need an api key
is it something like auth token to protect your python backend?
@James4u is it something like auth token to protect your python backend?
Sarabi dogOP
yea something like that
@Sarabi dog in order to make request to the backend to get some json data u need an api key
huh, then it's always visible
@James4u huh, then it's always visible
Sarabi dogOP
okay but for that we are using nect js api rouets right? which means it will be managed by the server
wait wait, is it auth token or API_KEY to use your service
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 ???????
accessToken vs API_KEY which one are you referring to?
nope
@James4u wait wait, is it auth token or API_KEY to use your service
Sarabi dogOP
using a simple API Key authentication mechanism, not OAuth or a more complex token-based authentication system.
it can't be used for web-sockets
Nile Crocodile
Yes that's what I'm trying to tell him
@Sarabi dog using a simple API Key authentication mechanism, not OAuth or a more complex token-based authentication system.
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
Sarabi dogOP
mmh we didn't implemented signin/sign out yet
cuz i wanna make it accessible for everyone
cuz i wanna make it accessible for everyone
@James4u just be clear if it's API_KEY or auth token
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"
}'
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"
}'
will you use HTTP request?
not websocket?
Sarabi dogOP
so my architecture supports both:
WebSocket connections for real-time, event-driven communication
RESTful HTTP endpoints for standard CRUD operations
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.
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
@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
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.
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.
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
Nile Crocodile
That were my words which been thrown behind their back 😑
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
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
@James4u `so hitting your api route will create websocket connection, right?`
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.
@James4u `so hitting your api route will create websocket connection, right?`
Nile Crocodile
Which is a horrible scenario 😅
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
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
@James4u and also ADD auth to your system - after login, provide higher API_KEY
Sarabi dogOP
so we can't make it secure without user authentication
lol authenticated system is not 100% secure
what can we expect from un-authed system in terms of security??
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?
@James4u what can we expect from un-authed system in terms of security??
Sarabi dogOP
tough question
@Sarabi dog 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?
Sarabi dogOP
@Nile Crocodile what solution u wanna provide
cuz at the end u are handling it
@Sarabi dog 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?
actually real time data doesn't means websocket
what kind of data do you want to show in the real time?
@James4u what kind of data do you want to show in the real time?
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
I feel like what you are saying is more close to streaming AI
@James4u I feel like what you are saying is more close to streaming AI
Sarabi dogOP
yes kinda
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.
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.
sorry I think I misunderstood your meaning
so what's real time user coordinates?
user geolocation?
@James4u I feel like what you are saying is more close to streaming AI
Nile Crocodile
It's not it's been delivered to you like that but it's not.
@James4u user geolocation?
Sarabi dogOP
yess
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? 🤣
@James4u oh, how can he move fast to get different results from the server while server is preparing something for the user
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
once u go there u ask what are some restaurants nearby
in that case we need ur geolocation data
yes?
Nile Crocodile
Lol it's chat website that needs your location data to make some calculation.
@Nile Crocodile Lol it's chat website that needs your location data to make some calculation.
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
no no my point is that
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 ?
why don't you get user's location when they request something?
@James4u why don't you get user's location when they request something?
Sarabi dogOP
yes, i did this configuration
but somehoe u guys are saying that api will be visible
so only if u request
well, I think you misunderstood
@Nile Crocodile Lol it's chat website that needs your location data to make some calculation.
Sarabi dogOP
at the end u will see a small ai model instead of the api
Nile Crocodile
You are mixing the points
yeah mixing two points
they are independant things
Sarabi dogOP
okay tell me what i am missing
so let me adjust the flow
Sarabi dogOP
ok
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
@James4u you can get his location - you don't need to make another request again to get user location
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?
Sarabi dogOP
yes
@Sarabi dog u got his location by requesting to the frontend?
request is something from client/browser to the server/api route
Sarabi dogOP
so to process the data backend needs geolocation data, right<'
@Sarabi dog so to process the data backend needs geolocation data, right<'
Sarabi dogOP
my point is how it will get from
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
Sarabi dogOP
so for each request we are making a geolocation request as backend needs right?
yeah, exactly
Sarabi dogOP
right now the project is structured like this
@Nile Crocodile so what i did wrong
@Nile Crocodile so what i did wrong
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
@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
Sarabi dogOP
so instead of making the request to the browser(client) where it makes request?
@Sarabi dog so instead of making the request to the browser(client) where it makes request?
am not sure if it's actually making a request - but yeah it must be
maybe to vercel service?
does it matter?
Nile Crocodile
Nooooo
It doesn't matter
@Nile Crocodile Nooooo
Sarabi dogOP
??
@Nile Crocodile It doesn't matter
Sarabi dogOP
so whats ur solution, and what u want me to change
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
@James4u but if you don't deploy your project on Vercel you are not able to use this api
Sarabi dogOP
are there rate limits for this api?
@Sarabi dog so whats ur solution, and what u want me to change
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
@Sarabi dog are there rate limits for this api?
no no totally not usable
you need to use alternative ways to get geolocation data from the http request data
@James4u and preocess send the response
Sarabi dogOP
i believe right now its structured like this
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
@Sarabi dog i believe right now its structured like this
you said server is making request to the browser to get user's geolocation
@James4u you said server is making request to the browser to get user's geolocation
Sarabi dogOP
yes cuz i am using socketIO for that
from browser? what if user declines?
@James4u from browser? what if user declines?
Sarabi dogOP
they can't access to our platform
@James4u not at all I think
Nile Crocodile
The browser has gps in it or not ?
Sarabi dogOP
to use our ai chatbot
@Nile Crocodile The browser has gps in it or not ?
Sarabi dogOP
it asks u to give permission
Nile Crocodile
I mean a gps api
okay that makes sense
Nile Crocodile
The gps is on the device
Sarabi dogOP
so here's the point, instead of making request to the browser where should i send the request
you don't need to make any request
@James4u you don't need to make any request
Sarabi dogOP
u are getting all at once?
browser will be sending the geolocation data with the query at once
Answer
@James4u browser will be sending the geolocation data with the query at once
Sarabi dogOP
okay, what if he moves to another place after an hour, will the geo data be same or different
if he starts a new query, browser will be sending the new geolocation
@James4u if he starts a new query, browser will be sending the new geolocation
Sarabi dogOP
right now it works like this but uses socket
tell me if i am wrong @Nile Crocodile
Nile Crocodile
No need for socket
Sarabi dogOP
ok instead of socket what to modify
thats where i got stuck
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
is everything clear now guys?
🙂
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
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
hmm didn't follow you - can you tell me your problem exactly?
@Sarabi dog 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
do you have any action that gets triggered initially? like when you refresh your page?
not initially but only if u reload the page
it's not related to the websocket I believe
@James4u to clarify websocket is when you want to get real time events from the server
again, websocket is only for this
@Sarabi dog not initially but only if u reload the page
hit the backend everytime you refresh the page
what's the problem? we have
useEffect(() => {}, []);
right?
Sarabi dogOP
yes
Nile Crocodile
@Sarabi dog are you trying to clear the session?
Sarabi dogOP
yes,
only the chat history
oh please don't ask to ask
gimme the problem @Sarabi dog @Nile Crocodile 😞
it keeps our conv long and long
Sarabi dogOP
can we talk?
if possible
just tell me
@Sarabi dog yes,
Nile Crocodile
What if his network connection lost ??
@Nile Crocodile What if his network connection lost ??
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
just tell me the UX feature you want to build/improve
@James4u just tell me the UX feature you want to build/improve
Sarabi dogOP
@Nile Crocodile
do u want me to provide api endpoint details?
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?
Sarabi dogOP
alright
thanks a lot
yr welcome