Nestjs + Passportjs Dynamic state.

Bogdan Lupu
2 min readMar 4, 2020

--

You are having a hard time with nest and passport, right?
You probably already have 20 tabs with this topic opened, right? :):D.
Well, let’s just dive in. “Talk is cheap. Show me the code.” ― Linus Torvalds

Here is the Authentification controller:

Facebook strategy

And the Authentication module

Now let’s explain a little bit :D.
The controller and the strategy are pretty standard. The trick is in the middleware configuration. OAuth has this feature called state parameter: https://auth0.com/docs/protocols/oauth2/oauth-state. This state param is passed through the login flow.

Now, in our code, by using another middleware before the passport one we can set this state dynamically. In this way, we are able to call http://localhost:3000/auth/facebook/login?state=what-do-you-want
and the state query will be passed down to the strategy and callback.

Tip: you can pass a JSON object encoded with base64 and decode the JSON in the backend.

Here is the git with the example:

PS: star my cool nestjs lib: https://github.com/lupu60/nestjs-toolbox

I see that it’s cool to have logos and nice pictures on medium, so:

--

--