I am working on a Next.js project with authentication and am putting some URLs as strings into an array called protectedRoutes, so people get redirected when they access those URLs before they sign in.
const protectedRoutes = ["/home", "/profile", etc.];
I also got some posts to display in my project where each post will have its own page.
Each post has a unique id stored in firebase and I had set up the router query already in Next.js.
Let say I have a post.id == "BjPDBvsWIsa11l6JxFOAgzR3mnG3" so its URL would be /post/BjPDBvsWIsa11l6JxFOAgzR3mnG3.
My question is, how do I store each post’s URL into the protectedRoutes array? Is there a way I can do this with Regex?
Thank you very much.
const postURL = new RegExp("/post/")
const protectedRoutes = ["/home", "/profile", postURL];
is not working.
Edit 29/3:
I also wish to avoid the following:
const postID = getPostID() // function that fetches post IDs from firebase
postID.forEach((id) => {
protectedRoutes.push(`/post/${id}`);
});
so to avoid making a long array once the number of posts grows, which slows down the search.
Edit 30/3:
Below shows the file containing protectedRoutes and the component that handles redirection.
In my _app.js,
import PrivateRoute from "@/components/PrivateRoute";
import { AuthProvider } from "@/contexts/AuthContext";
import "@/styles/globals.css";
export default function App({ Component, pageProps }) {
const protectedRoutes = ["/home", "/profile"];
const publicRoutes = [
"/",
"/sign-in",
"/sign-in/phone",
"/sign-up",
"/reset-password",
];
return (
<AuthProvider>
<PrivateRoute
protectedRoutes={protectedRoutes}
publicRoutes={publicRoutes}
>
<Component {...pageProps} />
</PrivateRoute>
</AuthProvider>
);
}
and in my PrivateRoute.jsx,
import { useEffect } from "react";
import { useRouter } from "next/router";
import { useAuth } from "@/contexts/AuthContext";
import FullPageLoader from "./FullPageLoader";
export default function PrivateRoute({
protectedRoutes,
publicRoutes,
children,
}) {
const router = useRouter();
const { currentUser, loading } = useAuth();
const pathIsProtected = protectedRoutes.indexOf(router.pathname) !== -1;
const pathIsPublic = publicRoutes.indexOf(router.pathname) !== -1;
useEffect(() => {
if (!loading && !currentUser && pathIsProtected) {
router.push("/sign-in");
}
if (!loading && currentUser && pathIsPublic) {
router.push("/home");
}
}, [currentUser, loading, pathIsProtected, pathIsPublic]);
if ((loading || !currentUser) && pathIsProtected) {
return <FullPageLoader />;
}
if ((loading || currentUser) && pathIsPublic) {
return <FullPageLoader />;
}
return children;
}
2
Answers
Test follow code,
Edit your app.js,
Edit your PrivateRoute.jsx,