next-auth handling session expired from backend golang

i want to handle token expired from backend in next js and save the token in session next-auth and cookie , but i have the problem when the token from backend is expired , i have no idea to delete the token when every 401 response code from backend and redirect to login in the client side, this is my code , in this case i don’t want to decode the token

import CredentialProvider from 'next-auth/providers/credentials'

export const authOptions = {
  providers: [
    CredentialProvider({
      id: 'credentials-1',
      name: 'Credentials-2',
      type: 'credentials',
      credentials: {},
      async authorize(credentials) {
        const { pn, password } = credentials
        try {
                   
          const res = await fetch(`${process.env.API_URL}/login`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(body)
          })

          const data = await res.json()
          if (res.status === 200) {
            return { ...data, credentialType: '1' }
          } else {
            throw new Error(JSON.stringify(data))
          }
        } catch (e) {
          throw new Error(e.message)
        }
      }
    }),
    CredentialProvider({
      id: 'credentials-2',
      name: 'Credentials-2',
      type: 'credentials',
      credentials: {},
      async authorize(credentials) {
        const { pn, password } = credentials
        try {
         
         
          const res = await fetch(`${process.env.API_URL}/login2`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(body)
          })

          const data = await res.json()
          if (res.status === 200) {
            return { ...data, credentialType: '2' }
          } else {
            throw new Error(JSON.stringify(data))
          }
        } catch (e) {
          throw new Error(e.message)
        }
      }
    })
  ],
  secret: 'Secret',
  session: {
    strategy: 'jwt',
    maxAge: 2 * 60 * 60
  },

  jwt: {
    secret: 'Secret',
    encryption: true
  },

  pages: {
    signIn: {
      'credentials-1': '/login',
      'credentials-2': '/login2'
    }
  },

  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.credentialType = user.credentialType

        if (user.credentialType === '1') {
          token.name = user.data.data_user.name
          token.email = user.data.data_user.email
          token.pn = user.data.data_user.pn
          token.status = user.data.data_user.status
          token.branch = user.data.data_user.branch
          token.token = user.data.token
        } else if (user.credentialType === '2') {
          token.name = user.data.data_user.nama
          token.pn = user.data.data_user.pn
          token.role = user.data.data_user.role
          token.branch = user.data.data_user.branch
          token.token = user.data.token
        }
      }
      return token
    },

    async session({ session, token }) {
      if (token) {
        session.user.name = token.name
        session.user.pn = token.pn
        session.user.branch = token.branch
        session.token = token.token
        session.credentialType = token.credentialType

        if (token.credentialType === '1') {
          session.user.email = token.email
          session.user.status = token.status
        } else if (token.credentialType === '2') {
          session.user.role = token.role
        }
      }

      return session
    }
  }
}

i have try to using to delete the cookie but doesn’t work, this is my code to request from the client side to handle every request in next js using use server, so anyone to help me ?


'use server'

import { getServerSession } from 'next-auth'
import { authOptions } from '@/libs/auth'
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'
import { useRouter } from 'next/navigation'

const CustomDispatch = async (url, req) => {
  try {
    const router = useRouter()
    const session = await getServerSession(authOptions)
    const token = session.token
    const requestOptions = {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        Authorization: `Bearer ${token}`
      },
      body: JSON.stringify(body),
      cache: 'no-store'
    }

    const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/${url}`, requestOptions)
    const responseData = await res.json()

    if (res.status === 401) {
      const response = NextResponse.redirect('/login')
      const allCookies = cookies().getAll()
      allCookies.forEach(cookie => {
        response.cookies.set(cookie.name, '', { maxAge: 0, path: '/' })
      })
      router.refresh()
      return response
    }

    return responseData
  } catch (error) {
    console.error('Error:', error)
    return null
  }
}

export default CustomDispatch


New contributor

Ujang Pudin 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