Best place to put refresh logic/authentication logic with the SDK

Hello, currently writing an app where I did a lot of authentication myself.

It works fine, but it’s decently buggy after several attempted fixes so I’m migrating it to authentication using the SDK.

Docs look clear, implementation looks straight-forward, but wondering about a few things.

  1. Is the client a shared singleton? If I create the client in one file and use it in another, do I get access to the same instance of the client? Is a context required?

  2. I use middleware right now to determine if someone is authenticated (based on a cookie) and then if they aren’t I redirect them to log in. Is there a way to do this with the Directus SDK?

  3. I re-log someone in automatically using the refresh token in cookies. Is this supported?

Thanks!

1 Answer

1
  1. The client is not a shared singleton, ensuring a singleton is left as an implementation details.
  2. You can attempt an sdk.getToken(), if it successful they are logged in.
  3. Same as #2, you can call sdk.getToken().

#2 and #3 are assuming you went through the login flow using the sdk, if not you can utilize the sdk.readMe() and sdk.refresh() functions respectively instead

Thanks for the response. In React, do you recommend context, or something else? Can I call sdk.getToken() in NextJS middleware? Does the SDK handle auto login if a refresh token exists? Or would that still be up to me.

I am not familiar enough with react or next.js to recommend anything specific. I would refer to our sample implementation of authentication with next.js as a good starting point. The sdk does handle auto refresh if the original login was done with the authentication composable.