Skip to content

next-refresh-token is a lightweight library for managing and refreshing access tokens in Next.js applications integrated with next-auth.

License

Notifications You must be signed in to change notification settings

yshen-max/Next-Refresh-Token

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


next-refresh-token

next-refresh-token is a lightweight library for managing and refreshing access tokens in Next.js applications integrated with next-auth.

Features

  • Automatic access token refresh using your backend's API.
  • Simple token management for access and refresh tokens.
  • Easy integration with next-auth.

Installation

Install the package using npm:

npm install next-refresh-token

Usage

Step 1: Modify your next-auth configuration

Update your pages/api/[...nextauth].js file to include custom token management using next-refresh-token:

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import TokenManager from "next-refresh-token/lib/tokenManager";

const tokenManager = new TokenManager();

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    async jwt({ token, account }) {
      if (account) {
        // Set tokens when first signed in
        tokenManager.setTokens(account.access_token, account.refresh_token);
      }
      return token;
    },
    async session({ session, token }) {
      session.accessToken = tokenManager.getAccessToken();
      session.refreshToken = tokenManager.getRefreshToken();
      return session;
    },
  },
});

Step 2: Set up token refresh logic

In your _app.js file, use TokenRefresher to automatically refresh the access token at regular intervals.

import TokenRefresher from "next-refresh-token/lib/refresh";
import { useEffect } from "react";

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    const refresher = new TokenRefresher("/api/refresh-access-token", 10 * 60 * 1000); // 10 minutes interval
    refresher.start(document.cookie.refreshToken, (newAccessToken) => {
      console.log("Access token refreshed:", newAccessToken);
    });

    return () => refresher.stop();
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;

Step 3: Backend endpoint for token refresh

Ensure your backend provides an endpoint for refreshing the access token. For example:

@Get('refresh-access-token')
async refreshAccessToken(@Req() request: Request) {
  const refreshToken = request.cookies.refreshToken;
  const newAccessToken = await getNewAccessTokenFromRefreshToken(refreshToken);
  return { accessToken: newAccessToken };
}

Example Project

A complete example is included in the /examples/next-auth-integration/ directory. To run the example:

  1. Navigate to the example directory:

    cd examples/next-auth-integration
  2. Install dependencies:

    npm install
  3. Start the development server:

    npm run dev

This will start a Next.js application that uses next-refresh-token for managing access and refresh tokens.


Testing

To ensure the library is working as expected, you can run the included tests. The tests cover the key features of next-refresh-token, such as token management and refresh logic.

Run tests

From the root directory of the project, run:

npm test

Example Tests

Here are some sample tests included in the tests/ directory.

Test: Token Refresher

tests/refresh.test.js

const TokenRefresher = require("../lib/refresh");

test("should throw error when refresh token is missing", () => {
  const refresher = new TokenRefresher("/api/refresh-token");
  expect(() => refresher.start(null, jest.fn())).toThrow("Refresh token is required");
});

test("should refresh token correctly", async () => {
  const refresher = new TokenRefresher("/api/refresh-token", 5000);
  const mockCallback = jest.fn();

  global.fetch = jest.fn(() =>
    Promise.resolve({
      ok: true,
      json: () => Promise.resolve({ accessToken: "newAccessToken" }),
    })
  );

  refresher.start("testRefreshToken", mockCallback);
  await new Promise((resolve) => setTimeout(resolve, 5500)); // Wait for the interval
  refresher.stop();

  expect(mockCallback).toHaveBeenCalledWith("newAccessToken");
});

Test: Token Manager

tests/tokenManager.test.js

const TokenManager = require("../lib/tokenManager");

test("should set and get tokens correctly", () => {
  const manager = new TokenManager();
  manager.setTokens("testAccessToken", "testRefreshToken");

  expect(manager.getAccessToken()).toBe("testAccessToken");
  expect(manager.getRefreshToken()).toBe("testRefreshToken");
});

API Documentation

TokenManager

A utility class for managing tokens.

  • setTokens(accessToken, refreshToken): Sets the access and refresh tokens.
  • getAccessToken(): Retrieves the current access token.
  • getRefreshToken(): Retrieves the current refresh token.

TokenRefresher

A class for automating token refresh.

  • start(refreshToken, callback): Starts the automatic token refresh process.
    • refreshToken: The refresh token to be sent to the backend.
    • callback: A function to handle the new access token.
  • stop(): Stops the automatic token refresh process.

License

This project is licensed under the MIT License. See the LICENSE file for details.


About

next-refresh-token is a lightweight library for managing and refreshing access tokens in Next.js applications integrated with next-auth.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published