-->

How to use MongoDB Stitch Auth in isomorphic or SS

2020-06-18 06:44发布

问题:

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?

回答1:

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.