Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hjortur17's avatar

connect ECONNREFUSED ::1:8000

Hello!

I'm trying to make my Nextjs frontend talk to my Laravel backend. But I get this error message when trying to generate CSRF token. connect ECONNREFUSED ::1:8000

I have tried to change the host between localhost and 127.0.0.1 but still the same issue.

Here is my Axios instance

import Axios from 'axios'

const axios = Axios.create({
    baseURL: 'http://localhost:8000',
    headers: {
        // 'X-Requested-With': 'XMLHttpRequest',
        'Accept': 'application/json',
        'Origin': 'http://localhost:3000',
    },
    withCredentials: true,
    withXSRFToken: true
})

export default axios

Here is my onSubmit function for the submit form

const onSubmit = async (data: RegisterFormSchema) => {
    setSubmitting(true);

    try {
      const result = await axios.post('/api/auth/register', { ...data });

      if (result.status === 201) {
        router.push('/innskra');
      }

      setTimeout(() => {
        setSubmitting(false);
      }, MINIMUM_ACTIVITY_TIMEOUT);
    } catch (error) {
      setSubmitting(false);
    }
  };

And here is the api route that eventually talks to my Laravel backend

const csrf = () => axios.get("/sanctum/csrf-cookie");

export async function POST(req: Request) {
  try {
    const { name, email, password, passwordConfirmation } = await req.json();

    if (password !== passwordConfirmation) {
      return NextResponse.json(
        { message: "Password and password confirmation do not match" },
        { status: 400 }
      );
    }

    // Get the CSRF token
    await csrf();

    // Register user on the backend
    const user = await axios.post("/register", {
      name,
      email,
      password,
      password_confirmation: passwordConfirmation,
    });

    return NextResponse.json(user.data, { status: 201 });
  } catch (err: any) {
    return NextResponse.json(
      { message: err.message || "Internal server error" },
      { status: 500 }
    );
  }
}

And here is my .env if needed:

BACKEND_URL=http://127.0.0.1:8000

NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=X
0 likes
2 replies
LaryAI's avatar
Level 58

The error connect ECONNREFUSED ::1:8000 indicates that your application is trying to connect to the backend on the IPv6 loopback address ::1 (which is equivalent to localhost in IPv6) but the connection is being refused. This typically means that the backend server is not running or not listening on the expected port.

Here are a few steps to troubleshoot and resolve this issue:

  1. Ensure the Laravel Backend is Running: Make sure your Laravel backend server is running and listening on port 8000. You can start the Laravel server using:

    php artisan serve --host=127.0.0.1 --port=8000
    
  2. Check Network Configuration: Ensure that your backend server is configured to accept connections from 127.0.0.1 and not just localhost. Sometimes, binding to localhost might not bind to 127.0.0.1 or ::1.

  3. Update Axios Configuration: Since you are using localhost in your Axios configuration, try explicitly using 127.0.0.1 to avoid any potential issues with IPv6 resolution:

    import Axios from 'axios';
    
    const axios = Axios.create({
        baseURL: 'http://127.0.0.1:8000',
        headers: {
            'Accept': 'application/json',
            'Origin': 'http://localhost:3000',
        },
        withCredentials: true,
        withXSRFToken: true
    });
    
    export default axios;
    
  4. Check Firewall and Security Software: Ensure that no firewall or security software is blocking the connection to 127.0.0.1:8000.

  5. Verify Backend URL in .env: Ensure that the BACKEND_URL in your .env file is correctly set to http://127.0.0.1:8000:

    BACKEND_URL=http://127.0.0.1:8000
    
  6. Check Laravel CORS Configuration: Ensure that your Laravel backend is configured to accept requests from your frontend's origin (http://localhost:3000). You can configure CORS in the cors.php configuration file:

    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    
    'allowed_methods' => ['*'],
    
    'allowed_origins' => ['http://localhost:3000'],
    
    'allowed_origins_patterns' => [],
    
    'allowed_headers' => ['*'],
    
    'exposed_headers' => [],
    
    'max_age' => 0,
    
    'supports_credentials' => true,
    

By following these steps, you should be able to resolve the ECONNREFUSED error and successfully connect your Next.js frontend to your Laravel backend.

hjortur17's avatar

@laryai - Okay, I made some adjustments and now I'm getting 419 error and nothing in my Laravel logs

Please or to participate in this conversation.