OAuth with Fastify

abhinavsachdeva profile image Abhinav Sachdeva ・2 min read

I was recently trying to setup authentication using OAuth2 for the first time and chose my fastify as my web server. Honestly the amount of information about OAuth on the web is huge and some of it is obsolete, hence this post.


  • Register your app at Google Cloud Platform
  • Enable the Google+ API
  • Generate credentials - Client ID, Client secret
  • Setup the authorized origin(front-ends) and redirect(server-routes) URIs like so: Google OAuth

Serve a basic HTML page on port 3002. Tip: use Live server for a quick start.

    <!-- Fastify server runs on localhost:3000 -->
    <a href="http://localhost:3000/api/auth/google>
        Google Login

Install the fastify plugins required

npm i fastify-cors fastify-oauth2

Create a fastify server

const fastify = require("fastify")({});

Register the CORS plugin

fastify.register(require("fastify-cors"), {
    origin: "*" // allow all origins (BAD)

Regster the OAuth2 plugin (using Google OAuth in this example)

const oauthPlugin = require('fastify-oauth2');

fastify.register(oauthPlugin, {
    // Can be any valid variable name you prefer
    // Fastify instance will now have this as a property
    name: 'googleOAuth2', 

    // Gets user's full name, email and profile picture URL
    scope: ['profile email'], 

    credentials: {
        client: {
            id: process.env.GOOGLE_OAUTH_CLIENT_ID,
            secret: process.env.GOOGLE_OAUTH_CLIENT_SECRET

        // plugin-provided configurations for Google OAuth
        auth: oauthPlugin.GOOGLE_CONFIGURATION, 

    // This is automatically registered as a 
    // GET route in your app
    startRedirectPath: '/api/auth/google', 

    // Can be a relative path that serves HTML 
    // or an absolute URL to your front-end app
    callbackUri: 'http://localhost:3000/api/auth/google/callback'

Register a route where Google will callback (send the response)

fastify.get("api/auth/google/callback", {}, async  function (req, res) {
    // Fastify instance gets decorated with this method on OAuth plugin initialization
    const token =  await fastify.googleOAuth2.getAccessTokenFromAuthorizationCodeFlow(req);

    console.log({ token }); // Just for debugging

    // Redirect to a route serving HTML or to your front-end
    res.redirect("http://localhost:3002/?token="  + token.access_token)

And that's it!
Start the server. Launch the UI in a browser and click the link.


Editor guide
jenkasia profile image
Evgeniy Kasyan

How i can sign out with fastify-oauth2?