Hey folks, is there a guide like this anywhere for...
# ory-network
c
Hey folks, is there a guide like this anywhere for Ory? https://auth0.com/blog/complete-guide-to-react-user-authentication/ I’ve found and gone through https://www.ory.sh/login-spa-react-nextjs-authentication-example-api-open-source/ but where I am getting a bit lost is on how to ensure that a user is authenticated before accessing routes/pages, or how to securely store a session and pass it through to other pages or components
h
You don't need to worry about the session at all. Just call the SDK's
toSession()
(https://www.ory.sh/login-spa-react-nextjs-authentication-example-api-open-source/#react-hook-to-find-out-if-a-user-is-authenticated) function and you'll get the session. Other than Auth0, you don't need to worry about tokens or token storage or refreshing stuff. That's why (I think 😅) Ory is so awesome! We take away the complexity by doing it for you! Regarding your API routes, it works the same way. Use the SDK's
toSession()
to get the session (or an error if the user is not authenticated or still needs to do 2FA). Hope this helps 🙂
🙏 1
c
OK so say each page would need to check the session? Sorry for the potentially basic questions just trying to get my head around it! 🙂
Is there a way for me to get a bearer token from the session, to pass to the backend? Or another recommended way to pass credentials/token/cookie from the frontend to backend API’s?
r
You'd probably want to defer sections that require auth until the authentication check is done. In Next, you'd do that check as early as in your
_app.jsx
component, in Create React App, in your
App
component. If you have a shared layout, you can do it in there as well Page load -> check auth -> show loader (ideally show nothing if time is <~300ms and then fall back to loader) If the request failed or there's no session -> show signed out view Active session -> show signed in view
🙏 1
You can include the session cookie in every request to your backend by passing
credentials: include
in your fetch options (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) or
withCredentials: true
when using something like axios.
👏 1
c
OK great thanks Michael, that’s super helpful and makes sense! I’ll check that out and see how it can work with ApolloClient, appreciate the help! 😄
r
No problem! In Apollo Client (i assume you're using graphql), you'd use
Copy code
const link = createHttpLink({
  uri: '<path to your /graphql>',
  credentials: 'include'
});
https://www.apollographql.com/docs/react/networking/authentication/#cookie
c
Yep using GraphQL! Ah amazing. Then I would use the
ory
package and
toSession()
to validate the credentials in the backend as well right? Actually I think this answers my question (maybe) with the approach here https://github.com/ory/docs/blob/master/examples/typescript-express/src/middleware.ts