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

1 messages · Page 1 of 1 (latest)

timber fractal
#

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!

tawny flickerBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

normal hound
#

use Next.js api routes as proxy

timber fractal
normal hound
#

so the request flow will be like
frontend => Next.js api routes => your python backend

timber fractal
#

make sense, i wanna convince the same thing to my frontend guy, but somehow he disagree, u will join here shortly

#

@sharp mirage

#

u can talk now

sharp mirage
normal hound
timber fractal
#

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"
]
}
})

normal hound
#

well, @timber fractal @sharp mirage 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?

timber fractal
#

i dont think so, what i can provide is the backend link and the api key to get acess, so whats the issue?

acoustic steeple
normal hound
#

so what's API_KEY you guys saying?

timber fractal
normal hound
#

is it something like auth token to protect your python backend?

timber fractal
normal hound
timber fractal
normal hound
#

wait wait, is it auth token or API_KEY to use your service

sharp mirage
#

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 ???????

normal hound
#

accessToken vs API_KEY which one are you referring to?

#

nope

timber fractal
normal hound
#

it can't be used for web-sockets

sharp mirage
#

Yes that's what I'm trying to tell him

normal hound
#

and that's what I said, having token public is always fine

#

just be clear if it's API_KEY or auth token

timber fractal
#

mmh we didn't implemented signin/sign out yet

cuz i wanna make it accessible for everyone

timber fractal
#

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"
}'

normal hound
#

will you use HTTP request?

#

not websocket?

timber fractal
#

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.

normal hound
#

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

timber fractal
#

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.

normal hound
#

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

sharp mirage
#

That were my words which been thrown behind their back 😑

timber fractal
#

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

normal hound
#

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

timber fractal
sharp mirage
normal hound
#

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

timber fractal
#

for example i have added rate limits, if more than 5 requests per minutes he will get blocked for an hour lets say

timber fractal
normal hound
#

lol authenticated system is not 100% secure

#

what can we expect from un-authed system in terms of security??

timber fractal
#

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?

timber fractal
#

cuz at the end u are handling it

normal hound
#

what kind of data do you want to show in the real time?

timber fractal
#

send back to the backend to proces for the rest

normal hound
#

I feel like what you are saying is more close to streaming AI

sharp mirage
#

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.

normal hound
#

sorry I think I misunderstood your meaning

#

so what's real time user coordinates?

#

user geolocation?

sharp mirage
timber fractal
normal hound
#

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? 🤣

timber fractal
#

in that case we need ur geolocation data

normal hound
#

yes?

sharp mirage
#

Lol it's chat website that needs your location data to make some calculation.

timber fractal
#

if u are at home and then moved to some place, if u ask about nearby places, u will not get accurate data

normal hound
#

no no my point is that

sharp mirage
#

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 ?

normal hound
#

why don't you get user's location when they request something?

timber fractal
#

but somehoe u guys are saying that api will be visible

#

so only if u request

normal hound
#

well, I think you misunderstood

timber fractal
sharp mirage
#

You are mixing the points

normal hound
#

yeah mixing two points

#

they are independant things

timber fractal
#

okay tell me what i am missing

normal hound
#

so let me adjust the flow

timber fractal
#

ok

normal hound
#

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

timber fractal
normal hound
#

user ask a question and we obivously send this question to the server (in this case Next.js api route)

#

right?

timber fractal
#

yes

normal hound
timber fractal
#

so to process the data backend needs geolocation data, right<'

timber fractal
normal hound
#

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

timber fractal
#

so for each request we are making a geolocation request as backend needs right?

normal hound
#

yeah, exactly

timber fractal
#

right now the project is structured like this

@sharp mirage so what i did wrong

normal hound
#

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

timber fractal
normal hound
#

maybe to vercel service?

#

does it matter?

sharp mirage
#

Nooooo

#

It doesn't matter

timber fractal
timber fractal
normal hound
#

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

timber fractal
normal hound
#

and preocess send the response

normal hound
#

you need to use alternative ways to get geolocation data from the http request data

timber fractal
sharp mirage
#

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

normal hound
timber fractal
normal hound
#

from browser? what if user declines?

timber fractal
sharp mirage
timber fractal
#

to use our ai chatbot

timber fractal
sharp mirage
#

I mean a gps api

normal hound
#

okay that makes sense

sharp mirage
#

The gps is on the device

timber fractal
#

so here's the point, instead of making request to the browser where should i send the request

normal hound
#

you don't need to make any request

timber fractal
normal hound
#

browser will be sending the geolocation data with the query at once

timber fractal
normal hound
#

if he starts a new query, browser will be sending the new geolocation

timber fractal
#

tell me if i am wrong @sharp mirage

sharp mirage
#

No need for socket

timber fractal
#

ok instead of socket what to modify

#

thats where i got stuck

normal hound
#

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

normal hound
#

is everything clear now guys?

#

🙂

timber fractal
#

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

normal hound
#

hmm didn't follow you - can you tell me your problem exactly?

normal hound
timber fractal
#

not initially but only if u reload the page

normal hound
#

it's not related to the websocket I believe

normal hound
normal hound
#

what's the problem? we have useEffect(() => {}, []);

#

right?

timber fractal
#

yes

sharp mirage
#

@timber fractal are you trying to clear the session?

timber fractal
#

yes,

#

only the chat history

normal hound
#

oh please don't ask to ask

#

gimme the problem @timber fractal @sharp mirage 😞

#

it keeps our conv long and long

timber fractal
#

can we talk?

#

if possible

normal hound
#

just tell me

sharp mirage
timber fractal
#

it will only trigger if u reload while having connection

#

here in europe i dont think we will have network issues

normal hound
#

just tell me the UX feature you want to build/improve

timber fractal
#

do u want me to provide api endpoint details?

normal hound
#

thinking following questions are out of the original question and more related to your internal coversation

#

@timber fractal can you close this thread by marking a solution?

timber fractal
#

alright

steady coralBOT
# normal hound to clarify websocket is when you want to get real time events from the server
Mark an answer as the solution

To mark the message as solution:

  1. Hover over the message you want to mark as the solution.
  2. Right click the message Click the three dots that appear on the right side.
  3. You'll see a menu which should have the option of Apps. Hover Over it.
  4. Click on the Mark as Answer option.
    Note: If you don't see the Mark as Answer option or Apps option, restart/update your discord app!
tawny flickerBOT
timber fractal
#

thanks a lot