skip to Main Content

I’ve setup my ecommerce frontend in next js 13 (App directory) and backend in laravel with scantum.
I’m not using laravel breeze since admin users use laravel for backend CRUD operation.

I’m confused how/where to save the token returned by backend in next js frontend. So that i can use it for other GET/POST requests.

Can i use next-auth for this process ? I would be thankful if someone could share any ideas on this.

2

Answers


  1. Chosen as BEST ANSWER

    After researching for week I'm able to connect with scantum by the following method.

    If you are reading in future and have better approach feel free to post your answer.

    import NextAuth, { NextAuthOptions } from "next-auth"
    import CredentialsProvider from "next-auth/providers/credentials"
    import API from "@/lib/axios" //axios insgtance
    
    export const authOptions: NextAuthOptions = {
      providers: [
        CredentialsProvider({
          name: "Email and Password",
          credentials: {
            email: { label: "Email", type: "email", placeholder: "Your Email" },
            password: { label: "Password", type: "password" },
          },
          async authorize(credentials) {
            const res = await fetch(
              "http://your-api-url/sanctum/csrf-cookie",
              {
                method: "GET",
              }
            )
    
            const setCookieHeader = res.headers.get("set-cookie")
            // console.log("setCookieHeader", setCookieHeader)
            // you'll find your_site_session key in this console log
    
            const cookies = setCookieHeader?.split(", ")
    
            let sessionKey = null
            let xsrfToken = null
    
            for (const cookie of cookies!) {
              if (cookie.startsWith("your_site_session=")) {
                sessionKey = cookie.split("=")[1]
              } else if (cookie.startsWith("XSRF-TOKEN=")) {
                xsrfToken = cookie.split("=")[1]
              }
    
              if (sessionKey && xsrfToken) {
                break
              }
            }
            const data = {
              email: credentials?.email,
              password: credentials?.password,
            }
            try {
              const abc = await API.post("/login", data, {
                headers: {
                  Cookie: `your_site_session=${sessionKey}; XSRF-TOKEN=${xsrfToken}`,
                  "X-XSRF-TOKEN": xsrfToken,
                },
              })
              console.log(abc.data)
              return abc.data
            } catch (error) {
              console.log(error.response.status, error.message)
            }
    
            return null
          },
        }),
      ],
    }
    const handler = NextAuth(authOptions)
    export { handler as GET, handler as POST }
    
    
    

  2. If you need to store a Sanctum token in your frontend, you can do so using the following method.

    localStorage.setItem("sanctum_token", response.data.sanctum_token); 
    

    above method will store the sanctum token in local storage.
    you can access it whenever you need it using the following method,

    var sanctum_token = localStorage.getItem("sanctum_token");
    

    Let’s say you have to pass it in an axio API request, then you can do it like below.

    var sanctum_token = localStorage.getItem("sanctum_token");
    
    axios.request({
      headers: {
        Authorization: `Bearer ${sanctum_token}`
      },
      method: "GET",
      url: `/api/v2/test`
    }).then(response => {
      console.log(response.data);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search