Next.js Discord

Discord Forum

Need help with the dreaded CORS problem. Using Laravel 9 for the APIs and Next 13 on the frontend

Answered
GuitarNerd posted this in #help-forum
Open in Discord
Avatar
Hi everyone!

I started working on a Next.js and Laravel app. I know it would be better to just use Next.js but it's not something that is possible at the moment.

Currently I'm developing locally but I'm unable to send requests due to CORS. Typically installing laravel-cors solves my issue but now that comes standards with Laravel 9. HandleCors is added in Kernel.php and cors.php is the following

<?php

return [

    'paths' => ['*', 'api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'], //also tried allowed_origins => ['http://localhost:3000'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false, //also tried true

];

   


I also tried adding a proxy in package.json.

Rewrites in next.config.js stopped the CORS problem but for some reason it did not take into account the fetch method provided and it was causing my request to become GET despite it being a POST request.

/** @type {import('next').NextConfig} */
const nextConfig = {
    async rewrites() {
        return [
            {
                source: '/api/:path*',
                destination: 'http://localhost:8000/api/:path*',
            },
        ]
    },
}

module.exports = nextConfig


Any ideas on what else i can do ?
Thanks a lot!
Answered by GuitarNerd
@tafutada777 I solved it by using formdata isntead of Json.stringify
View full answer

4 Replies

Avatar
Rewrites in next.config.js stopped the CORS problem but for some reason it did not take into account the fetch method provided and it was causing my request to become GET despite it being a POST request.

im not clear what you mean. can u elaborate this?
Plus, open the Chrome Dev Tool, go ahead Network tab. locate the fetch rerquest that fails, share the screen capture of the response failed.
then, you might want to understand what CORS is, how to tweak HTTP response headers to avoid CORS error.
make use of cURL command, which allows you to see the details of HTTP response headers.
Avatar
@tafutada777 I solved it by using formdata isntead of Json.stringify
Answer