DEV Community

Ben Taylor
Ben Taylor

Posted on

Safer Authentication with TypeScript

I’ve been going through the Auth0 tutorial on Cloudflare Workers and integrating it with my own codebase. One of the first things I noticed was how loose the use of types was in the example code. This isn’t necessarily bad, it’s a tutorial, it’s not written in TypeScript, and the audience is just wanting to get something to work. But to me authentication is mission critical, which means I want to be confident about my types.

Let’s look at one of the first functions they have you implement:

carbon-21

This piece of code is pretty neat. One thing I like about it is that it returns a tuple. The first thing in the tuple is whether it was authorized or not, and the second thing is either the authorization information or the redirect information. What this means is that we can guard against the first item in the tuple and then use the second item.

But, unfortunately, TypeScript gets something different when it infers types for this function:

(boolean | {authorization:any})[] | (boolean | {redirectUrl:any})[]
Enter fullscreen mode Exit fullscreen mode

Typescript thinks that this is an Array of either (boolean or an authorization object) OR it’s an Array of either (boolean or a redirect object). That’s messy! It means we can’t be confident that the implementation is correct. It would be valid to write it with the boolean flipped around, or with the object on either side. It also means we can’t use the types of this function to be confident that we’re only using the return type in the right way. For example to use the authorization object we will have to use a type assertion on it:

carbon-23

We have to do this because the type of data is:

boolean | { authorization: any } | { redirectUrl: any }
Enter fullscreen mode Exit fullscreen mode

If someone made a mistake with the if statement here the type assertion would prevent any type errors from being raised.

We can improve the situation by encoding information about the sorts of return values the authorize function can have within the return type.


The full text of this post is available on my Substack, where I go into how we can use the right types to make this safer.

Safer Authentication with Typescript

Thanks for reading!

Top comments (0)