-
Notifications
You must be signed in to change notification settings - Fork 389
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Protect Page Route in NextJS #148
Comments
As I understood you should check the session in serverless methods in getInitialProps or in getServerSideProps (or in your routes of the custom server). And when the session doesn't exist you will redirect the user to the login route (before page will be rendered). For example:
|
Hey @ImranAhmed |
@rogelio-meza-t That looks perfect. Will give that a try. Thanks. |
@rogelio-meza-t I managed to get that working however as soon as I added a getStaticProps to my page I got the following error.
I think this refers back to the HOC with-auth.jsx which uses getInitialProps. Any ideas how to move past this? |
so I finally got this working. With HOC
With getInitialProps
With getServerSideProps
|
For those who come across this issue in a search, I shared my solution to this problem in another comment: #132 (comment) The comment explains the implementation of a Example Usageimport React from 'react'
import { withSession, useSession } from '../utils/session-provider'
function DashboardPage(props) {
const session = useSession()
console.log(props.hello) // 'hello from getInitialProps'
// You can use `session.accessToken` to make an authenticated request on the client
// Could be with useEffect, or your own useApi, useQuery, or whatever
const data = useApi('/dashboard', session.accessToken)
return (
<Dashboard data={data} />
)
}
DashboardPage.getInitialProps = async function (context) {
const { session } = context;
// You can use `session.accessToken` to make an authenticated request on first page load
// This works for both server and client requests
// Here, you'd have to use `fetch` or `axios`, or whatever else directly.
const data = await fetch('/api/dashboard', session.accessToken)
return {
message: 'hello from getInitialProps',
}
}
export default withSession(DashboardPage) |
What about using CSR? I do not saw any examples when using client side rendering. |
what about middlewares? |
Using instructons in readme there is an example at bottom of page on a HOC that can be used to protect API routes requireAuthentication . Is there anything similar for pages? If not how would one best protect access to a page?
The text was updated successfully, but these errors were encountered: