Alex
Alex

Reputation: 143

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.

Upvotes: 3

Views: 2184

Answers (2)

Borduhh
Borduhh

Reputation: 2185

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.

Upvotes: 7

Emil
Emil

Reputation: 1280

You can make hoc which will wrap your protected component and check if he is authenticated by a server. If not redirect him to homepage or somewhere else.

Upvotes: 0

Related Questions