John
John

Reputation: 55

How to protect routes, not to be accessed directly through URL?

//this route is define in app.js
<Route path="/edit" component={Edit}/>
 //this is navlink
<NavLink  to={{pathname:"/edit",state:{index:index}}}>Edit</NavLink>
 // class
class Edit extends Component {


constructor(props){
    super(props)

    this.state = {

        index:props.location.state.index,
        title:'',

    };
}

componentDidMount(){


    axios.get("http://localhost:5000/gettitle",{headers: {token: Cookies.get('adtoken')}})
    .then(response => {

        this.setState({
            title:response.data.jobs[this.state.index].title,


        })



    })
    .catch(error => {
        console.log(error)
    })


} 
render() {

}
}

export default Edit;

When I click on this Navlink it moves to /edit with props, but when I directly write /edit through URL it gives errors because it is accessing /edit component without props

How can I protect /edit so that it cant be accessed directly through URL? Thanks

Upvotes: 0

Views: 427

Answers (3)

Abdelrhman Arnos
Abdelrhman Arnos

Reputation: 1442

You can use PrivateRoute component:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      props?.location.state?.index ? (
        <Component {...props} />
      ) : (
        <Redirect to="/404" />
      )
    }
  />
);

Here an example

Upvotes: 1

Max Gram
Max Gram

Reputation: 695

It does seem like you are using React Router, thus my answer will be for that library.

In order to protect /edit you could trigger <Redirect /> if props are missing.

EditPage component would look something like this:

import React from 'react'
import { Redirect } from 'react-router-dom'

const EditPage = ({ index }) => {
  if(index){
    return <Redirect to="/" />
  } else {
    return <div>my protected page</div>
  }
}
export default EditPage

Upvotes: 0

Rahul Jain
Rahul Jain

Reputation: 429

If you are using react-router-v3 or less you can use Route onEnter callback

<Route onEnter={checkIfValidUrl}></Route>

and in callback function you will get get replace function. which you can use to redirect to desire page.

const checkIfValidUrl = (nextState, replace, cb) => {
  // Your condition goes here.
}

But if you are using react-router-v4 or higher can create a High order component (HOC) to check if that route is valid route or not.

If your application supports server side rendering you can write code on server to handle this scenario.

Upvotes: 0

Related Questions