Combine an OAuth2 authorization code movement technique for the Spotify Net API in a NodeJS with TypeScript and NestJS again finish utility
When constructing an API, one of the crucial vital elements of the appliance is the safety and authentication of its customers. Most frameworks present some pointers on tips on how to implement completely different authentication methods. NestJS, for example, presents, in its official documentation, the JWT technique.
Nonetheless, one extensively unfold authentication technique is the OAuth2 method, normally used with third celebration providers resembling Fb, Google and Spotify accounts which gives a method to make use of an present account in these providers to authenticate the consumer and even work together with these providers on behalf of the authenticated consumer.
As there is no such thing as a official documentation for integrating one of these authentication with NestJS and growth articles normally deal with Google and Fb integration, this text presents a substitute for combine the Spotify Authorization Code Flow with NestJS utilizing the Passport authentication middleware together with the passport-spotify technique.
This text focuses on the method of utilizing the OAuth2 technique for Spotify built-in with a NestJS utility, subsequently, the next necessities are thought-about to be fulfilled earlier than the method described on this article:
- A NestJS utility bootsraped with its fundamental construction. For this half, it’s enough to comply with the short setup information within the NestJS documentation;
- A Spotify account with entry to the Spotify Developer Dashboard and an app registered with its
CLIENT ID
andCLIENT SECRET
credentials. Following the step-by-step official documentation on tips on how to use the Spotify API is enough for this text.
If you’re not accustomed to the OAuth2 Authorization Code Stream, please verify the guide provided by the Spotify Web API documentation.
With a NestJS utility prepared, an auth
useful resource have to be created utilizing the next command — contemplating that the Nest CLI is put in within the machine:
nest g mo auth
nest g s auth --no-spec
nest g co auth --no-spec
These instructions create an auth
folder with fundamental module, service, and controller information with none .spec information. With all in place, the folder construction ought to seem like this:

Now, the next dependencies have to be put in:
npm set up @nestjs/passport @nestjs/jwt passport passport-jwt passport-spotifynpm set up -D @sorts/passport-jwt @sorts/passport-spotify
To any extent further, there are 3 functionalities that have to be accessible within the utility when it comes to authentication:
- Login of customers utilizing the Spotify OAuth2 authorization code movement;
- Retrieving the consumer’s data from Spotify and generate a JWT;
- Utilizing the JWT technique in order that there is no such thing as a want for connecting with the Spotify OAuth2 server each time there’s a necessity for consumer authentication in throughout a session.
For the primary and second functionalities described earlier, there must be a controller with the routes /login
and /redirect
:
The above code comprehends the next:
- Each routes,
/login
and/redirect
are guarded with theSpotifyOauthGuard
custom guard which implements thepassport-spotify
technique that shall be described later; - The login methodology/route is the endpoint that customers will entry to provoke the authentication;
- The
spotifyAuthRedirect
methodology (‘/redirect’ route) is the URL to which the Spotify OAuth2 service shall be redirected as soon as the consumer efficiently logs in; - The
spotifyAuthRedirect
methodology: retrieves the consumer’s data coming from Spotify positioned thereq.consumer
property — if there is no such thing as a data, which means the authentication wasn’t carried out or failed, the strategy redirects the request to the login route once more — units theconsumer
req property to undefined (as it’s shall be outlined because the JWT payload additional), generates a JWT with it, and returns the consumer’s data and Spotify tokens that can be utilized by the appliance to entry routes within the Spotify Net API utilizing the consumer’s data relying on the scopes defined.
When utilizing a built-in passport technique, a customized guard mustbe created and likewise its corresponding technique. The SpotifyOauthGuard
is solely a category that extends the AuthGuard
class, so, after making a ‘/guards’ folder, inside it, the SpotifyOauthGuard
ought to seem like this:
Additionally, the named spotify
technique have to be created inside a /methods
folder:
The above code is answerable for connecting with the Spotify OAuth2 service and managing the redirection to the appliance. The method is:
- The
SpotifyOauthStrategy
class extends thePassportStrategy
utilizing the technique supplied by the passport-spotify lib and title it ‘spotify’ so theSpotifyOauthGuard
can establish it; - The constructor methodology calls the passport-spotify Technique constructor methodology utilizing the tremendous() methodology, passing the Spotify app credentials
CLIENT_ID
andCLIENT_SECRET
(saved in .env vars as they need to not be uncovered publicly), better described here, a callback URL which is identical route outlined within the auth.controller.ts,/redirect
, and the scopes that the app wants for interacting with the consumer’s data; - The
tremendous()
methodology additionally has a callback perform, that shall be referred to as as quickly because the consumer’s login course of succeeds and earlier than it’s redirected to the appliance. This perform provides to the request that shall be made to the/redirect
route the next properties: consumer (containing the consumer’s profile data) and authInfo (containing therefreshToken
,accessToken
andexpires_in
data).
As soon as the technique is applied, the consumer shall be redirected to the /redirect URL, and, in auth.controller.ts
(introduced earlier), the spotifyAuthRedirect
methodology will intercept the req object and extract the consumer
and authInfo
properties and move the consumer
to the authService
. With the consumer’s data, the login
methodology within the AuthService
class is answerable for producing the JWT. The auth.service.ts ought to seem like:
Lastly, in auth.service.ts
, the /redirect
route returns an object containing the authInfo
and consumer properties in addition to a header Authentication set to ‘Bearer ’ concatenated with the JWT.
This a part of the authentication is mainly as described within the official NestJS documentation. For this half, there must be outlined in your .env
vars a JWT_SECRET
, which is a string that’s used to generate and encrypt/decrypt the JWT’s that the appliance generates and should not be uncovered publicly. Much like the Spotify technique, it’s essential to create a JwtAuthGuard
class that extends the built-in passport AuthGuard together with a corresponding, named jwt
. Contained in the /guards
folder, create the jwt-auth.guard.ts
file as the next:
And the corresponding technique, contained in the /methods folder, ought to seem like:
The above code is executed when a route is adorned with the JwtAuthGuard
. The tremendous()
methodology extracts the JWT supplied by the request to a guarded route, decrypts it with the JWT_SECRET
supplied and inserts a consumer
property into the req object containing the data that was beforehand inserted into the payload of the JWT.
It’s vital to spotlight that the inserted consumer
property will not be the identical that the spotify-strategy
inserts to the req
object, and that is the rationale why within the spotifyAuthRedirect
methodology, the req.consumer
property is about to undefined earlier than the sign up with the jwt technique.
Now any authenticate route will be adorned with the JwtAuthGuard
as the next:
With all the things in place, it’s time to configure the instantiation of all of the modules. The AuthModule
class ought to seem like this:
The auth.module.ts
file defines all of the suppliers of the auth useful resource and registers the JWT_SECRET
in the course of the instantiation of the JwtModule
in addition to the expiration time for it, right here outlined as 3600s (1 hour).
Additionally, the AppModule ought to seem like:
The app.module.ts
instantiates all of the modules of the appliance together with the ConfigModule
, which is important for utilizing all of the env vars described within the course of.
The ultimate state of the folders and information of the appliance ought to seem like this:

The OAuth2 is an attention-grabbing method of integrating an utility with exterior apps resembling widespread social media providers, profiting from a straightforward option to log customers in addition to offering functionalities to the customers associated to those apps.
Although NestJS doesn’t present an official method of constructing this type of integration, there are a lot of open supply initiatives that goals to make it simpler this authentication methodology resembling those described and used on this article.