React Router and CSP

React Router and CSP

React Router requires specific considerations for CSP, especially when using hash-based routing or dealing with navigation:

// Configuring React Router with CSP
import { BrowserRouter, Routes, Route } from 'react-router-dom';

// Custom Router with CSP considerations
function CSPAwareRouter({ children, nonce }) {
  // Configure router to work with CSP
  const routerConfig = {
    // Use browser history instead of hash history
    // Hash history can trigger CSP violations with inline event handlers
    basename: process.env.PUBLIC_URL,
  };
  
  return (
    <BrowserRouter {...routerConfig}>
      {/* Inject nonce into route context */}
      <NonceProvider value={nonce}>
        {children}
      </NonceProvider>
    </BrowserRouter>
  );
}

// Safe link component that respects CSP
function CSPSafeLink({ to, children, ...props }) {
  const navigate = useNavigate();
  
  const handleClick = (e) => {
    e.preventDefault();
    // Use programmatic navigation instead of href javascript:
    navigate(to);
  };
  
  return (
    <a href={to} onClick={handleClick} {...props}>
      {children}
    </a>
  );
}