Created
December 19, 2021 12:27
-
-
Save gyfchong/3f3dab62de1832e7ce9f066c78dc30fd to your computer and use it in GitHub Desktop.
How to make a reusable getServerSideProps function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pages/protected.js | |
import protectRoute from "utils/protect-route"; | |
export async function getServerSideProps({ req }) { | |
return await protectRoute(req, (user) => { | |
return { props: { user } }; | |
}); | |
} | |
// protect-route.js | |
import { supabase } from "@supabase"; | |
const protectRoute = async (req, callback) => { | |
const { user } = await supabase.auth.api.getUserByCookie(req); // use any auth provider you want | |
if (!user) { | |
return { props: {}, redirect: { destination: "/sign-in" } }; | |
} | |
return callback?.(user) ?? { props: {} }; | |
}; | |
export default protectRoute; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment