How to use MongoDB Stitch Auth in isomorphic or SSR app?
Asked Answered
B

1

7

Would like to use Stitch in a NextJS app (basically isomorphic react). Normally, you would be able to pass a JWT or session token in the headers of the initial request, and if the user already has a session you can immediately load all of their data and hydrate the app on the server.

With Google Firebase Auth you can even do this by passing a token in the request and collecting the user on the server side using that token.

I'm not sure how this would work with Stitch, though. Documentation says Stitch creates a token that's stored in local storage. Is there anyway to pass this to the server to use to authenticate a user on the server?

Also, the SDK for stitch isn't isomorphic. There is a server and a browser SDK. Can one only handle user sessions in the browser? That would seem to make it difficult to use for server rendered apps. Am I missing something?

Banter answered 3/1, 2019 at 18:37 Comment(3)
I am having same issue. Have you found any answer to thisHarvin
I moved on from trying to use this library, but it's an ongoing issue on their github. The issue is located here: github.com/mongodb/stitch-js-sdk/issues/186Banter
Yes. I am also looking on #186.However i got some link which might be useful for developer who are facing same issue in future. LinkHarvin
M
0

You can access the token (auto refreshes by stitch) in app.user.activeUserAuthInfo.accessToken

On server side you will decode the token and get something like this.

{
  "exp": 1590658522,
  "iat": 1590656722,
  "iss": "5ecf66e9d230045ab06a867b",
  "stitch_devId": "eqwewqewqeq",
  "stitch_domainId": "dewdewwqwewq",
  "sub": "5ecf524c65adwdwedw4ac1185510cff", <---- this is your user ID 
  "typ": "access"
}

You can find 'sub' which is your ObjectId(_id) that you can use to get data from your mongodb.


Stitch is serverless. Meaning you can get rid of the server totally. You can create-react-app, build your app with Stitch functions -> Build -> Upload all your static files and then leave everything running. Without any server, and without any worries on scaling your server.

If you want SSR, and you still want to process it on your own hosted server, don't bother using stitch.

If you are intending to use nextjs with server less, better to use lamda@edge and then build your files with serverless-nextjs component. And then you get rid of stitch all together and use Cognito or firebase.

https://www.serverless.com/blog/serverless-nextjs/

Lamda@edge does not have free tier though.

Mahan answered 28/5, 2020 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.