Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to secure content in React Route with Authentication?

I'm trying to setup a protected route (homepage in my case) with React. It works fine on the client. If not authenticated by server, it reroutes to login page. But technically, unauthenticated users can still check out the static content on the protected route (though of course the api calls to server are safe), just by either sifting through code, or by setting state in dev tools. I don't like this.

TLDR question: How can I make sure even the static content in protected routes are not seen by unauthenticated users?

I understand that authentication has to move from client to the server. But what is the proper way to do this with React/React Router?

My ideas:

-Serve an unauthenticated react app/index.html for just Login. When authenticated, serve another app for user content/pages.

-Maybe it's possible to do some component lazy loading from the server that also checks authentication on the request?

My context: create-react-app, express/node backend, using okta auth.

Thank you.

like image 932
Alex Avatar asked Nov 18 '25 09:11

Alex


1 Answers

There are a couple of ways around this using a variety of methods.

First is to server-side render everything with a framework like Next.js. This framework is used by a ton of large enterprise companies because of the search engine friendliness of SSR pages. In your scenario though, it would solve your problem of showing content only when someone is authorized.

However, in most React.js apps, your data is coming from a data source such as MongoDB that is hidden behind your backend. The only code/information an unauthorized user would be able to see in your JS is the general layout of pages.

like image 74
Borduhh Avatar answered Nov 20 '25 00:11

Borduhh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!