DEV Community

Discussion on: Next.js Authentication - JWT Refresh Token Rotation with NextAuth.js

Collapse
 
tasmiarahmantanjin profile image
Tasmia Rahman

Hi, Thanks for your tutorial this is really good and explains a lot. Currently i am trying add refreshToken to my company project, In my case we want to set i a bit differently. For example the requirement is I need to send accessToken and refreshToken from backend Normally with res.body then Frontend need to set it in Header and then I need to get the refreshToken in auth/refresh-token endpoint with req.headers. I am a bit confused how to achieve this. Do you think it's possible? Any help will be highly appreciated. thanks a lot in advance!

Collapse
 
mabaranowski profile image
Mateusz Baranowski

On the server, I use express-jwt package, which takes care of reading the authorization header. On the client, you can set the auth header, with accessToken taken from useSession:

axios.get(API_URL + 'endpoint', {
                headers: {
                    'Authorization': `Bearer ${session.accessToken}`
                }
            })
Enter fullscreen mode Exit fullscreen mode

Do You want to refresh the token from the client code?

Collapse
 
tasmiarahmantanjin profile image
Tasmia Rahman

Thanks a lot Mateusz for the reply! I was able to achieve what i wanted to, front nextauth.js I called the refresh-token end point. Now, I am trying logOut on refreshToken error, and refreshTokeExpire. Because of the initial project setup I am still trying out the best way to logOut user on refreshTokenExpire. I noticed you used useAuth hook, I am struggling to use in correct place on my code! As this is my very first task on nextauth therefor it´s seems a bit hard to me!

Thread Thread
 
mabaranowski profile image
Mateusz Baranowski

You can call the useAuth hook directly from the page (pages folder).

export default function Page() {
    const isAuthenticated = useAuth(true);

    return (
        <>
            {isAuthenticated ?
                <YourComponent />
                : null}
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

In the example above, we use isAuthenticated to decide if we should render the page. If you do not need this functionality, calling useAuth(true) should be sufficient. This hook will log out the user when his token expires while being on that page.

Thread Thread
 
tasmiarahmantanjin profile image
Tasmia Rahman

Thanks Mateusz! I got it, but my boss wants me to call auto logout inside nextauth.js.
`
events: {
session: async ({ session }) => {
// if RefreshAccessTokenError then logout
if (session?.error === 'RefreshAccessTokenError') {
signOut()
}

  // if refreshTokenExpiresIn then signOut
  if (
    session?.refreshTokenExpiresIn &&
    Date.now() > new Date(session.refreshTokenExpiresIn).getTime()
  ) {
    console.log('I am logging out')
    signOut()
  }
}
Enter fullscreen mode Exit fullscreen mode

}
`

I kanda figure one way out which is using session event like below. He don't want to call hooks on pages. However with event I am getting a error message also like error - unhandledRejection: ReferenceError: window is not defined .That's why it's a bit complicated in my case!

Thread Thread
 
mabaranowski profile image
Mateusz Baranowski

You are getting "window is not defined" because you are trying to call a signOut function (which requires a browser window) in a session callback inside [...nextauth].js.

[...nextauth].js lives in pages/api/auth, and pages/api in Next.js are the server functions. You can look up the documentation on signOut.

If you want to logout a user from the session callback, you should probably use POST /api/auth/signout. Call it as you would a regular endpoint. This is used by signOut() internally.

I'm not sure if it's gonna work, but it's worth exploring. Let me know how you did :)