Refreshing access token automatically?

I’m building a dashboard using Next, Auth js and the Spotify API. I’ve implemented the OAuth flow and the user connects with the Spotify account correctly.
Spotify after the authentication process gives you an access token and a refresh token, because the access token expires after 1 hour.
You can use the refresh token to get another access token and I would like to do that automatically, but for some reasons it doesn’t work.

This is what I did in auth.ts, basically I followed the documentation.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import NextAuth, { DefaultSession } from "next-auth";
import Spotify from "next-auth/providers/spotify";
declare module "next-auth" {
interface Session extends DefaultSession {
access_token?: string;
expires_at?: number;
refresh_token?: string;
error?: "RefreshAccessTokenError";
}
}
declare module "@auth/core/jwt" {
interface JWT {
access_token: string;
expires_at: number;
refresh_token: string;
error?: "RefreshAccessTokenError";
user?: DefaultSession["user"];
}
}
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Spotify({
clientId: process.env.AUTH_SPOTIFY_ID,
clientSecret: process.env.AUTH_SPOTIFY_SECRET,
authorization: `https://accounts.spotify.com/authorize?scope=user-read-private user-read-email user-top-read user-read-recently-played user-library-read`,
}),
],
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user; // !! is used here to convert the potentially truthy/falsy value of auth?.user to a strict boolean representation
const isOnDashboard = nextUrl.pathname.startsWith("/dashboard");
if (isOnDashboard) {
if (isLoggedIn) return true;
return false; // redirect authenticated users to login page
} else if (isLoggedIn) {
return Response.redirect(new URL("/dashboard", nextUrl));
}
return true;
},
async jwt({ token, account, user }) {
if (account) {
console.log("New authentication, creating new token");
return {
...token,
access_token: account.access_token,
expires_at: Math.floor(
Date.now() / 1000 + (account.expires_in || 3600)
),
refresh_token: account.refresh_token,
user,
};
} else if (Date.now() < token.expires_at * 1000) {
console.log("token still valid, returning existing token");
return token;
} else {
console.log("token expired, trying to refresh");
if (!token.refresh_token) throw new Error("Missing refresh token");
try {
const response = await fetch(
"https://accounts.spotify.com/api/token",
{
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: process.env.AUTH_SPOTIFY_ID!,
client_secret: process.env.AUTH_SPOTIFY_SECRET!,
grant_type: "refresh_token",
refresh_token: token.refresh_token,
}),
method: "POST",
}
);
const tokens = await response.json();
if (!response.ok) throw tokens;
console.log("token refreshed successfully, returning updated token");
return {
...token,
access_token: tokens.access_token,
expires_at: Math.floor(
Date.now() / 1000 + (tokens.expires_in || 3600)
),
refresh_token: tokens.refresh_token || token.refresh_token,
};
} catch (error) {
console.error("Error refreshing access token", error);
return { ...token, error: "RefreshAccessTokenError" as const };
}
}
},
session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
session.access_token = token.access_token as string;
}
return session;
},
},
});
</code>
<code>import NextAuth, { DefaultSession } from "next-auth"; import Spotify from "next-auth/providers/spotify"; declare module "next-auth" { interface Session extends DefaultSession { access_token?: string; expires_at?: number; refresh_token?: string; error?: "RefreshAccessTokenError"; } } declare module "@auth/core/jwt" { interface JWT { access_token: string; expires_at: number; refresh_token: string; error?: "RefreshAccessTokenError"; user?: DefaultSession["user"]; } } export const { handlers, signIn, signOut, auth } = NextAuth({ providers: [ Spotify({ clientId: process.env.AUTH_SPOTIFY_ID, clientSecret: process.env.AUTH_SPOTIFY_SECRET, authorization: `https://accounts.spotify.com/authorize?scope=user-read-private user-read-email user-top-read user-read-recently-played user-library-read`, }), ], callbacks: { authorized({ auth, request: { nextUrl } }) { const isLoggedIn = !!auth?.user; // !! is used here to convert the potentially truthy/falsy value of auth?.user to a strict boolean representation const isOnDashboard = nextUrl.pathname.startsWith("/dashboard"); if (isOnDashboard) { if (isLoggedIn) return true; return false; // redirect authenticated users to login page } else if (isLoggedIn) { return Response.redirect(new URL("/dashboard", nextUrl)); } return true; }, async jwt({ token, account, user }) { if (account) { console.log("New authentication, creating new token"); return { ...token, access_token: account.access_token, expires_at: Math.floor( Date.now() / 1000 + (account.expires_in || 3600) ), refresh_token: account.refresh_token, user, }; } else if (Date.now() < token.expires_at * 1000) { console.log("token still valid, returning existing token"); return token; } else { console.log("token expired, trying to refresh"); if (!token.refresh_token) throw new Error("Missing refresh token"); try { const response = await fetch( "https://accounts.spotify.com/api/token", { headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: process.env.AUTH_SPOTIFY_ID!, client_secret: process.env.AUTH_SPOTIFY_SECRET!, grant_type: "refresh_token", refresh_token: token.refresh_token, }), method: "POST", } ); const tokens = await response.json(); if (!response.ok) throw tokens; console.log("token refreshed successfully, returning updated token"); return { ...token, access_token: tokens.access_token, expires_at: Math.floor( Date.now() / 1000 + (tokens.expires_in || 3600) ), refresh_token: tokens.refresh_token || token.refresh_token, }; } catch (error) { console.error("Error refreshing access token", error); return { ...token, error: "RefreshAccessTokenError" as const }; } } }, session({ session, token }) { if (session.user) { session.user.id = token.id as string; session.access_token = token.access_token as string; } return session; }, }, }); </code>
import NextAuth, { DefaultSession } from "next-auth";
import Spotify from "next-auth/providers/spotify";

declare module "next-auth" {
  interface Session extends DefaultSession {
    access_token?: string;
    expires_at?: number;
    refresh_token?: string;
    error?: "RefreshAccessTokenError";
  }
}

declare module "@auth/core/jwt" {
  interface JWT {
    access_token: string;
    expires_at: number;
    refresh_token: string;
    error?: "RefreshAccessTokenError";
    user?: DefaultSession["user"];
  }
}

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Spotify({
      clientId: process.env.AUTH_SPOTIFY_ID,
      clientSecret: process.env.AUTH_SPOTIFY_SECRET,
      authorization: `https://accounts.spotify.com/authorize?scope=user-read-private user-read-email user-top-read user-read-recently-played user-library-read`,
    }),
  ],
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user; // !! is used here to convert the potentially truthy/falsy value of auth?.user to a strict boolean representation
      const isOnDashboard = nextUrl.pathname.startsWith("/dashboard");
      if (isOnDashboard) {
        if (isLoggedIn) return true;
        return false; // redirect authenticated users to login page
      } else if (isLoggedIn) {
        return Response.redirect(new URL("/dashboard", nextUrl));
      }
      return true;
    },

    async jwt({ token, account, user }) {
      if (account) {
        console.log("New authentication, creating new token");
        return {
          ...token,
          access_token: account.access_token,
          expires_at: Math.floor(
            Date.now() / 1000 + (account.expires_in || 3600)
          ),
          refresh_token: account.refresh_token,
          user,
        };
      } else if (Date.now() < token.expires_at * 1000) {
        console.log("token still valid, returning existing token");
        return token;
      } else {
        console.log("token expired, trying to refresh");
        if (!token.refresh_token) throw new Error("Missing refresh token");

        try {
          const response = await fetch(
            "https://accounts.spotify.com/api/token",
            {
              headers: { "Content-Type": "application/x-www-form-urlencoded" },
              body: new URLSearchParams({
                client_id: process.env.AUTH_SPOTIFY_ID!,
                client_secret: process.env.AUTH_SPOTIFY_SECRET!,
                grant_type: "refresh_token",
                refresh_token: token.refresh_token,
              }),
              method: "POST",
            }
          );

          const tokens = await response.json();
          if (!response.ok) throw tokens;

          console.log("token refreshed successfully, returning updated token");

          return {
            ...token,
            access_token: tokens.access_token,
            expires_at: Math.floor(
              Date.now() / 1000 + (tokens.expires_in || 3600)
            ),
            refresh_token: tokens.refresh_token || token.refresh_token,
          };
        } catch (error) {
          console.error("Error refreshing access token", error);
          return { ...token, error: "RefreshAccessTokenError" as const };
        }
      }
    },
    session({ session, token }) {
      if (session.user) {
        session.user.id = token.id as string;
        session.access_token = token.access_token as string;
      }

      return session;
    },
  },
});

Right now when I’m logged in, after one hour, if I refresh the page it will give me a fetch error(I’m fetching some data to display in the main page of the dasboard). It happens because the access token was not refreshed correctly. If I refresh the error page again, then it will work and display the data correctly.

What I want to achieve is refreshing the token automatically, without having errors, so the user can stay on the main page as long as he wants and refresh the data whenever he wants.

This is how I’m getting the access token in the page and use it to fetch:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export default async function Page() {
const session = await auth();
if (!session?.user) return null;
console.log("Session:", session); // Log the session object
console.log("Access Token:", session.access_token); // Log the access token
const accessToken = session.access_token ?? "";
</code>
<code>export default async function Page() { const session = await auth(); if (!session?.user) return null; console.log("Session:", session); // Log the session object console.log("Access Token:", session.access_token); // Log the access token const accessToken = session.access_token ?? ""; </code>
export default async function Page() {
  const session = await auth();

  if (!session?.user) return null;

  console.log("Session:", session); // Log the session object
  console.log("Access Token:", session.access_token); // Log the access token

  const accessToken = session.access_token ?? "";

Thank you!

New contributor

Eduard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật