Cors Issue on My Next JS APP

Hi

I wanted to build an Flask Next JS app like it is in Next.js Flask Starter – Vercel

When I make a get request to the server I will get a Cors Error.

My App: https://markb-52h2naa5g-mark-baumanns-projects.vercel.app/

Frontend:

// app/page.tsx
'use client';  // Add this directive at the top

import { useEffect, useState } from 'react';

const HomePage = () => {
  const [data, setData] = useState<string>('');

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://markb-4j93a7cux-mark-baumanns-projects.vercel.app/api/python');
        const text = await response.text();
        console.log(text);
        setData(text);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>Response from Flask API:</h1>
      <div dangerouslySetInnerHTML={{ __html: data }} />
    </div>
  );
};

export default HomePage;

Backend:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Dies aktiviert CORS für alle Routen

@app.route("/api/python")
def hello_world():
    return "<p>Hello, World!</p>"

if __name__ == "__main__":
    app.run(port=5000)

next Config:

module.exports = {
  async headers() {
    return [
      {
        // matching all API routes
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "https://markb-4j93a7cux-mark-baumanns-projects.vercel.app/" },
          { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
          { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
        ]
      }
    ]
  }
};

Vercel.json:


{
  "headers": [
    {
      "source": "/api/(.*)",
      "headers": [
        { "key": "Access-Control-Allow-Credentials", "value": "true" },
        { "key": "Access-Control-Allow-Origin", "value": "https://markb-4j93a7cux-mark-baumanns-projects.vercel.app/" },
        { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
        { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
      ]
    }
  ]
}

Full Code on GitHub GitHub - mark-baumann/markb

Hi, @mark-baumann!

CORS issues are interesting. I wonder if we can align the project more to be like the Next.js Flask Starter template. Could be a start :bulb:

Otherwise, you could try looking at your proxy set-up to forward all /api requests from the frontend to the Flask backend. Instead of using the full URL, we’re now using a relative path /api/python.

On the front-end, you could rewrite the rule that forwards all requests from /api/* to your Flask backend. In development, it points to your local Flask server, and in production, it points to your deployed Flask app on Vercel.

For the back-end, maybe you can configure your Flask app to use port 5328 to match the starter template.

Could you give that a go and let us know how you get on?