I would like to have a section of my contentful + Gatsby + Netlify site to only be available to certain people. I'm not sure how to set up private routes with these instructions because of contentful--the routines are being dynamically created on the build. I can't figure out how to set just one or two of the sections to login and leave all the other public. Can someone make a suggestion or point me to a guide?
1 Answers
This is the important bit from the tutorial you linked.
I can't figure out how to set just one or two of the sections to login and leave all the others public. Can someone make a suggestion or point me to a guide?
Pick a route you want to make private for example /app/profile. This can be done purely in React:
//src/components/privateRoute.js
import React, { Component } from "react"
import { navigate } from "gatsby"
import { isLoggedIn } from "../services/auth"
const PrivateRoute = ({ component: Component, location, ...rest }) => {
if (!isLoggedIn() && location.pathname !== `/app/login`) {
navigate("/app/login")
return null
}
return <Component {...rest} />
}
export default PrivateRoute
You need to store login credentials somewhere. I would advise to use React content together with your authentication API. Here is a question that might help you.
// AuthContextProvider class:
import React from "react";
export const AuthContext = React.createContext();
export class AuthContextProvider extends React.Component {
state = {
authenticated: false,
toggleLogin: () => {},
userid: null,
};
render() {
return (
<AuthContext.Provider
value={{
authenticated: this.state.authenticated,
userid: this.state.userid,
toggleLogin: () => {
const previousValueState = this.state.authenticated;
this.setState(state => ({
authenticated: !previousValueState,
userid: 2,
}));
},
}}
>
{this.props.children}
</AuthContext.Provider>
);
}
}
And now you can edit your Router to use the PrivateRoute component:
//src/pages/app.js
import React from "react"
import { Router } from "@reach/router"
import Layout from "../components/layout"
import PrivateRoute from "../components/privateRoute"
import Profile from "../components/profile"
import Login from "../components/login"
const App = () => (
<Layout>
<Router>
<PrivateRoute path="/app/profile" component={Profile} />
<Login path="/app/login" />
</Router>
</Layout>
)
export default App
I would advise to not worry about Contentful. The concept about private routes is handled by Gatsby and React. CMSs like Contentful are irrelevant for private routes. You need to be more specific with your question if you want a more detailed answer for this part.
- 7,744
- 4
- 47
- 62