next-refresh-token
is a lightweight library for managing and refreshing access tokens in Next.js applications integrated with next-auth
.
- Automatic access token refresh using your backend's API.
- Simple token management for access and refresh tokens.
- Easy integration with
next-auth
.
Install the package using npm:
npm install next-refresh-token
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;
},
},
});
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;
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 };
}
A complete example is included in the /examples/next-auth-integration/
directory. To run the example:
-
Navigate to the example directory:
cd examples/next-auth-integration
-
Install dependencies:
npm install
-
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.
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.
From the root directory of the project, run:
npm test
Here are some sample tests included in the tests/
directory.
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");
});
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");
});
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.
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.
This project is licensed under the MIT License. See the LICENSE
file for details.