Session Sharing Between Symfony Backend and React Frontend Not Working

I’m developing a web application with a Symfony backend and a React frontend. My goal is to share the session between Symfony and React so I can dynamically render UI elements based on the user’s role or permissions in the React pages.

Despite my efforts, the authentication state in the React frontend is not updating correctly. The fetch request to the Symfony backend is made, but the response always indicates that the user is not authenticated in the React app, while the Symfony backend correctly recognizes the user as authenticated.

The API response from http://127.0.0.1:8000/api/check-auth returns {“authenticated”:true,”roles”:[“ROLE_ADMIN”,”ROLE_USER”]}
The React frontend remains { authenticated: false, roles: [] }

Steps I’ve Taken:
1.Set Up CORS Using NelmioCorsBundle:
nelmio_cors.yaml configuration:

nelmio_cors:
    defaults:
        allow_origin: ['http://localhost:3000']
        allow_headers: ['Content-Type', 'Authorization']
        allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
        allow_credentials: true
        max_age: 3600
    paths:
        '^/api/':
            allow_origin: ['http://localhost:3000']
            allow_headers: ['Content-Type', 'Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
            allow_credentials: true
            max_age: 3600

2.Configured Session Settings:
framework.yaml configuration:

framework:
    secret: '%env(APP_SECRET)%'
    session:
        handler_id: ~
        cookie_secure: auto
        cookie_samesite: lax
        storage_factory_id: session.storage.factory.native

  1. Created API Endpoint to Check Authentication Status:

    ApiController.php:

namespace AppController;

use PsrLogLoggerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentSecurityCoreSecurity;

class ApiController extends AbstractController
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    #[Route('/api/check-auth', name: 'api_check_auth', methods: ['GET'])]
    public function checkAuth(Security $security): JsonResponse
    {
        $user = $security->getUser();

        if ($user) {
            $this->logger->info('User roles: ' . implode(', ', $user->getRoles()));
            return new JsonResponse([
                'authenticated' => true,
                'roles' => $user->getRoles(),
            ]);
        }

        $this->logger->info('Unauthenticated access');
        return new JsonResponse([
            'authenticated' => false,
            'roles' => [],
        ]);
    }

    #[Route('/api/test-session', name: 'api_test_session', methods: ['GET'])]
    public function testSession(Request $request): JsonResponse
    {
        $session = $request->getSession();
        if (!$session->has('test')) {
            $session->set('test', 'value');
            return new JsonResponse(['message' => 'Session set']);
        }

        return new JsonResponse(['message' => 'Session value: ' . $session->get('test')]);
    }
}

4.React Hook to Fetch Authentication Status:

useAuth.js:
import { useState, useEffect } from 'react';

const useAuth = () => {
    const [auth, setAuth] = useState({ authenticated: false, roles: [] });

    useEffect(() => {
        const checkAuth = async () => {
            try {
                const response = await fetch('http://127.0.0.1:8000/api/check-auth', {
                    credentials: 'include', // Include cookies in the request
                });
                const data = await response.json();
                setAuth(data);
            } catch (error) {
                console.error('Error:', error);
            }
        };

        checkAuth();
    }, []);

    useEffect(() => {
        console.log('Auth state changed:', auth);
    }, [auth]);

    return auth;
};

export default useAuth;

5.React Component Utilizing Authentication Hook:

about.jsx:
import React from 'react';
import useTextContent from '../hooks/useTextContent';
import useImageContent from '../hooks/useImageContent';
import useHeadingContent from '../hooks/useHeadingContent';
import useAuth from '../hooks/useAuth';

function About() {
    const { authenticated, roles } = useAuth();
    useTextContent();
    useImageContent();
    useHeadingContent();
    
    const isAdmin = roles.includes('ROLE_ADMIN');

    return (
        <div className="about-page-wrapper">
            {/* about-Page-Header start */}
            <div className="about-header about-header-s">
                <h1 className="header-text" data-page="about" data-tag="header">
                </h1>
                <h1 className="header-text" data-page="about" data-tag="testttt">
                </h1>
                <p data-page="about" data-tag="header"></p>
                <p data-page="about" data-tag="arrow"></p>
            </div>
            {/* about-Page-Header end */}
        </div>        
    );
}

export default About;

  1. Symfony Security Configuration:

    security.yaml:

security:
    password_hashers:
        SymfonyComponentSecurityCoreUserPasswordAuthenticatedUserInterface: 'auto'
    providers:
        app_user_provider:
            entity:
                class: AppEntityUser
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            lazy: true
            provider: app_user_provider
            form_login:
                login_path: app_login
                check_path: app_login
                default_target_path: /frequentQuestion/
            logout:
                path: app_logout
    access_control:
        - { path: ^/question, roles: ROLE_ADMIN }
        - { path: ^/frequentQuestion, roles: ROLE_ADMIN }

Despite these configurations, the authentication state in the React frontend remains { authenticated: false, roles: [] }, while the API response correctly indicates the user is authenticated.
Additional Information:

React Frontend URL: http://localhost:3000/
Symfony Backend URL: http://127.0.0.1:8000/

What I Need Help With:

Ensuring the session is correctly shared between the Symfony backend and React frontend.
Diagnosing why the authentication state is not updating correctly in the React frontend.

Additional Debugging Steps Taken:

Verified that the session cookie is set and sent with each request using browser developer tools.
Checked network requests to ensure that the session cookie is included.

New contributor

tree rex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật