skip to Main Content

I have a react and django app which is being served behind nginx. The /admin route and /api routes both point to uwsgi. However when loading these routes the react app is served unless a hard refresh of the page is peformed. It seems like react is serving all routes instead of just the index.

Is there a way to exclude routes in react so it will only display if the path is "/" or is there something in nginx/django config I can change to overcome this issue.

This is a snippet from my nginx conf:

    location / {
        try_files $uri $uri/ =404;
    }
    location /api/ {
        uwsgi_pass  uwsgi;
        include     /etc/nginx/uwsgi_params;
    }
    location /admin/ {
        uwsgi_pass  uwsgi;
        include     /etc/nginx/uwsgi_params;
    }

and my django urls config:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include(routers.urls))
]

Any ideas on how I could proceed would be appreciated

2

Answers


  1. It sounds like React is intercepting the onClick event of the links and preventing the browser from handling it normally.

    You can try altering the link tags so that they prevent React from doing that:

    <a href="/admin/" onClick={() => { location.href = "/admin/" }}>Admin</a>
    
    /* Or if using react router */
    <Link to="/admin/" onClick={() => { location.href = "/admin/" }}>Admin</Link>
    

    Is there a way to exclude routes in react so it will only display if the path is "/"…

    How are the routes added or configured in React? They should be changed to use the format I illustrated above, or deleted if you don’t want them to display at all.

    … or is there something in nginx/django config I can change to overcome this issue.

    Your nginx configuration is written correctly. You can test it here.

    Login or Signup to reply.
  2. I think i found the solution.

    1- update your react-scripts to ^v4

    2- add urls you don’t want to be cached to service-worker.js file:

    registerRoute(
       ({ request, url }) => {
    
          ...
    
          if (
             url.pathname.startsWith('/admin') ||
             url.pathname.startsWith('/api')
          ) {
             return false;
          }
    
          ...
    
          return true;
       },
       createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
    );
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search