how to share the symfony backend session with the react front end after logging in to the backend?

I am developing a web application with a Symfony backend and a React frontend. I’m trying to share the session between Symfony and React so that i can later on dynamically render UI elements in the react pages based on the backend user’s role or permissions.

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

down below is what i tried and didn’t work, so i am open to different solutions hopefully easy to implement

Here are the steps of the solution that i have tried:

  • I have set up CORS using NelmioCorsBundle to allow requests from my React frontend.
    Symfony Backend (nelmio_cors.yaml):
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

  • Configured session settings in framework.yaml.
    Symfony Session Configuration (framework.yaml):
framework:
    secret: '%env(APP_SECRET)%'
    http_method_override: true
    handle_all_throwables: true

    session:
        handler_id: ~
        cookie_secure: auto
        cookie_samesite: lax
        storage_factory_id: session.storage.factory.native

    php_errors:
        log: true

  • Created an API endpoint /api/check-auth to check authentication status.
    Symfony Controller (ApiController.php):
<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentSerializerSerializerInterface;
use SymfonyComponentSerializerNormalizerObjectNormalizer;
use SymfonyComponentSecurityCoreSecurity;

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

        if ($user) {
            return new JsonResponse([
                'authenticated' => true,
                'roles' => $user->getRoles(),
            ]);
        }

        return new JsonResponse([
            'authenticated' => false,
            'roles' => [],
        ]);
    }

}

  • Used a custom hook (useAuth) to fetch authentication status from the Symfony backend.
    React Hook (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
                });
                console.log('Response status:', response.status);
                if (response.ok) {
                    const data = await response.json();
                    console.log('Response data:', data);
                    setAuth(data);
                } else {
                    console.error('Failed to fetch authentication status:', response.statusText);
                }
            } catch (error) {
                console.error('Error:', error);
            }
        };

        checkAuth();
    }, []);

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

    return auth;
};

export default useAuth;

Symfony Login Form (security.yaml):

security:
    enable_authenticator_manager: true
    providers:
        in_memory:
            memory: ~

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            lazy: true
            provider: in_memory
            form_login:
                login_path: login
                check_path: login
            logout:
                path: logout
                target: /

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api, roles: ROLE_USER }

this is my react Test page (AuthTest.js):

import React from 'react';
import useAuth from './useAuth';

const AuthTest = () => {
    const auth = useAuth();

    return (
        <div>
            <h1>Auth Test</h1>
            <p>Authenticated: {auth.authenticated ? 'Yes' : 'No'}</p>
            <p>Roles: {auth.roles.join(', ')}</p>
        </div>
    );
};

export default AuthTest;

Despite these 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 the user is not authenticated.

the authentication state in React remains { authenticated: false, roles: [] }, while the result of going to ‘http://127.0.0.1:8000/api/check-auth’ is {“authenticated”:true,”roles”:[“ROLE_ADMIN”,”ROLE_USER”]}

i also tried using axios in the front end but it dident work properly.

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