Home / Blog / GitHub Login in Under 10 Mins with Nuxt Auth Utils
GitHub Login in Under 10 Mins with Nuxt Auth Utils

GitHub Login in Under 10 Mins with Nuxt Auth Utils

Daniel Kelly
Daniel Kelly
Updated: June 5th 2025

Adding social authentication to your Nuxt 3 application can significantly improve the user experience. Nuxt Auth Utils is a powerful module that simplifies this process, offering secured and sealed cookie sessions. This guide will walk you through setting up GitHub login with Nuxt Auth Utils.

What is Nuxt Auth Utils?

Nuxt Auth Utils is a module designed to add authentication to Nuxt applications with features like:

  • Hybrid Rendering support (SSR, CSR, SWR, Prerendering)
  • Support for over 40 OAuth Providers, including GitHub
  • Password Hashing and WebAuthn (passkey) support
  • A useUserSession() Vue composable for easy access to session state
  • Tree-shakable server utils for efficient bundling
  • An <AuthState> component for conditional rendering based on auth state

It's built with few dependencies, runs on multiple JavaScript environments (Node, Deno, Workers), and is fully typed with TypeScript.

Prerequisites

Before we begin, ensure you have a Nuxt 3 project.

  1. Add nuxt-auth-utils to your project:
    Open your terminal and run:

    npx nuxi@latest module add auth-utils
  2. Set your session password:
    Add a NUXT_SESSION_PASSWORD environment variable to your .env file. This password must be at least 32 characters long. Nuxt Auth Utils will generate one for you in development if it's not set. This password is used to encrypt and decrypt your session cookie.

    # .env
    NUXT_SESSION_PASSWORD=your-super-secure-password-with-at-least-32-characters

Configuring GitHub OAuth

To enable GitHub authentication, you need to provide your GitHub OAuth app's Client ID and Client Secret to Nuxt Auth Utils.

  1. Create a GitHub OAuth App:
    • Go to your GitHub Developer settings: https://github.com/settings/developers
    • Click "New OAuth App".
    • Application name: Choose a name (e.g., "My Nuxt App").
    • Homepage URL: Your application's homepage URL.
    • Authorization callback URL: For local development, it's typically http://localhost:3000/auth/github. For production, you can create a seperate Github Oauth App pointed to YOUR_PRODUCTION_DOMAIN/auth/github.
    • After creating the app, note down the Client ID and generate a Client Secret.
  2. Add credentials to your Nuxt config:
    You can configure the OAuth credentials in your nuxt.config.ts file via runtimeConfig in combination with environment variables. First the runtime config:

    // nuxt.config.ts
    export default defineNuxtConfig({
      modules: ["nuxt-auth-utils"],
      runtimeConfig: {
        oauth: {
          github: {
            clientId: "", // defaults to empty string
            clientSecret: "", // defaults to empty string
          },
        },
      },
    });
    

    Then use environment variables with a naming convention that matches the runtime config variable names (recommended to use .env vars for security and to support different oauth apps per environment instead of setting values directly in runtime config):

    # .env
    NUXT_OAUTH_GITHUB_CLIENT_ID=YOUR_GITHUB_CLIENT_ID
    NUXT_OAUTH_GITHUB_CLIENT_SECRET=YOUR_GITHUB_CLIENT_SECRET
    

Creating the GitHub Authentication Route

Next, create a server route that will handle the GitHub OAuth flow.

Create the file ~/server/api/auth/github.get.ts (or ~/server/routes/auth/github.get.ts if you prefer routes over api for organization):

// ~/server/api/auth/github.get.ts
export default defineOAuthGitHubEventHandler({
  async onSuccess(event, { user, tokens }) {
    await setUserSession(event, {
      user: {
        githubId: String(user.id),
        login: user.login,
        name: user.name,
        avatarUrl: user.avatar_url,
      },
      loggedInAt: Date.now(),
    });
    return sendRedirect(event, "/");
  },
  async onError(event, error) {
    console.error("GitHub OAuth error:", error);
    return sendRedirect(event, "/login-error");
  },
});

Important: Make sure your GitHub OAuth app's "Authorization callback URL" is set to http://<your-domain>/auth/github (or the path you chose, aligning with this server route, e.g., /api/auth/github).

Using the Session in Your Vue Components

Nuxt Auth Utils provides the useUserSession() composable to access the user's session data in your Vue components.

Here's an example of how you might use it in a component, for example, ~/components/TheHeader.vue:

<script setup>
const { loggedIn, user, clear} = useUserSession();

const loginWithGitHub = () => {
  // Redirect to the server route that initiates the GitHub OAuth flow
  window.location.href = "/api/auth/github";
};

const logout = async () => {
  await clear();
  // Optionally, redirect to homepage or login page
  // await navigateTo('/')
};
</script>

<template>
  <nav>
    <div v-if="loggedIn && user">
      Welcome, {{ user.name || user.login }}!
      <img
        v-if="user.avatarUrl"
        :src="user.avatarUrl"
        alt="User Avatar"
        width="30"
        height="30"
        style="border-radius: 50%; margin-left: 10px;"
      />
      <button @click="logout">Logout</button>
    </div>
    <div v-else>
      <button @click="loginWithGitHub">Login with GitHub</button>
    </div>
  </nav>
</template>

You can also use the <AuthState> component for a solution that works even on pre-rendered pages.

<script setup lang="ts">
const loginWithGitHub = () => {
  window.location.href = "/api/auth/github";
};
</script>
<template>
  <nav>
    <AuthState v-slot="{ user, clear, loggedIn }">
      <template v-if="loggedIn">
        Welcome, {{ user.name || user.login }}!
        <img
          v-if="user.avatarUrl"
          :src="user.avatarUrl"
          alt="User Avatar"
          width="30"
          height="30"
          style="border-radius: 50%; margin-left: 10px;"
        />
        <button @click="logout">Logout</button>
      </template>
      <template v-else>
        <button @click="loginWithGitHub">Login with GitHub</button>
      </template>
    </AuthState>
  </nav>
</template>

Type Augmentation (Optional)

To get proper type support for your custom fields in the user session, you can create a type declaration file (e.g., auth.d.ts) in your project root:

// auth.d.ts
declare module "#auth-utils" {
  interface User {
    githubId?: string;
    login?: string;
    name?: string;
    avatarUrl?: string;
    // Add any other custom fields you stored from GitHub
  }
  interface UserSession {
    loggedInAt?: number; // if you store this as a timestamp
    // Add any other custom fields to the session itself
  }
}

export {};

Conclusion

Setting up GitHub authentication in your Nuxt 3 application is straightforward with Nuxt Auth Utils. By configuring your GitHub OAuth application, setting up the server route, and utilizing the useUserSession composable or <AuthState> component, you can provide a seamless login experience for your users. Remember to keep your client secrets secure and manage session data responsibly.

For more advanced configurations and features, refer to the official Nuxt Auth Utils documentation.

If you’d like a step by step video walkthrough of this process plus a deeper dive into other features like username/password login and passkey login, checkout our complete video course: Nuxt Auth Utils.

Start learning Vue.js for free

Daniel Kelly
Daniel Kelly
Daniel is the lead instructor at Vue School and enjoys helping other developers reach their full potential. He has 10+ years of developer experience using technologies including Vue.js, Nuxt.js, and Laravel.

Comments

Latest Vue School Articles

A Custom Opinionated Event Handler for Nuxt API Endpoints with Guards And Validation Support

A Custom Opinionated Event Handler for Nuxt API Endpoints with Guards And Validation Support

Nuxt API endpoints are extremely useful! Boost your productivity with some handy conventions. Learn to create custom event handlers, advanced validation techniques with zod, and endpoints protection with guards.
Daniel Kelly
Daniel Kelly
LLM Agents: Your Guide to Smarter Development

LLM Agents: Your Guide to Smarter Development

Explore LLM agents and how they enhance developer workflows with smarter automation and decisions. A guide for devs!
Eleftheria Batsou
Eleftheria Batsou
VueSchool logo

Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.

More than 200.000 users have already joined us. You are welcome too!

Follow us on Social

© All rights reserved. Made with ❤️ by BitterBrains, Inc.