Production API not setting cookies for local frontend development

Help! I’m stuck with a tricky cookie problem. My buddy and I are building an app together. I’ve got the FastAPI backend deployed on Render, while his Next.js frontend is running locally.

We’re attempting to use session-based authentication with cookies, but the cookies never get set on the client side. I’ve tried a few adjustments:

  • Setting samesite to ‘none’
  • Enabling httponly and secure options
  • Tweaking CORS settings

Despite these attempts, I can’t seem to get the cookie to stick. Below is a simplified version of my login code:

@router.post('/login')
async def login(response: Response):
    # authentication logic
    response.set_cookie(
        'auth_token',
        token,
        httponly=True,
        secure=True,
        samesite='None',
        max_age=3600
    )
    return {'message': 'Logged in'}

And here’s my CORS configuration:

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*']
)

What could be causing the cookies to not save across these domains? Any help would be greatly appreciated!

hey there! have u tried using a specific origin instead of ‘*’ in ur CORS settings? something like ‘http://localhost:3000’ might work better. also, make sure ur frontend is actually sending credentials with requests - set the ‘credentials’ option to ‘include’ in ur API calls. good luck!

hm, interesting issue! have u tried checking ur browser’s console for any errors? sometimes it can give clues about why cookies aren’t sticking. also, maybe try temporarily disabling the ‘secure’ flag for local testing? just remember to turn it back on for production! what specific browser are u using, btw?

Have you considered the mismatch between your local environment and production setup? Since your frontend is running locally and the backend is on Render, there might be issues with protocol differences. Try setting up HTTPS locally for your Next.js app to match the production environment. You can use tools like mkcert for this.

Also, double-check your CORS configuration. Instead of using a wildcard for allow_origins, specify the exact origin of your local frontend. This might look something like:

allow_origins=[‘http://localhost:3000’]

Lastly, ensure your frontend is actually sending credentials with requests. In your API calls, you need to set the credentials option to ‘include’. Without this, the browser won’t send or accept cookies for cross-origin requests.

If these don’t work, you might want to consider using token-based authentication stored in local storage as a temporary workaround while debugging the cookie issue.