Fluxium
Fluxium

Reputation: 110

Server gets JWT from API, how can the client get the JWT from the server?

I'm working on authentication using Next.js and Strapi. The client sends a post request with credentials to the Next.js server. Then, the server sends a post request to the Strapi API, passing the credentials, to log the user in. The server gets a JWT token and sets it as an HTTPonly cookie.

My question is: How do I also receive the JWT on the client side to do some fetching? I'm not really sure how to do this.

Client sends post request with credentials to server:

// -- /pages/account/login.js
const handleLogin = (e) => {
    e.preventDefault()

    axios.post("/api/login", {
        identifier: `${credentials.email}`,
        password: `${credentials.password}`,
        remember: stayLoggedIn,
    })
    .then(response => {
        // I need to access the JWT here
        Router.push("/")
        response.status(200).end()
    }).catch(error => {
        console.log("Error reaching /api/login ->", error)
    })
}

Server calls Strapi API and logs the user in, receiving a JWT token and setting it as a cookie:

// -- /pages/api/login.js
export default (req, res) => {

const {identifier, password, remember} = req.body;

// Authenticate with Strapi
axios.post(`${API_URL}/api/auth/local`, {
    identifier, password
})
.then(response => {

    const jwt = response.data.jwt; // I need to pass this back to client
    console.log("Got token: ", jwt)

    // Set HTTPonly cookie
    if (remember === false) {
        res.setHeader(
            "Set-Cookie",
            cookie.serialize("jwt", jwt, {
                httpOnly: true,
                secure: process.env.NODE_ENV !== "development",
                maxAge: 60 * 60 * 24, // Logged in for 1 day
                sameSite: "strict",
                path: "/",
            })
        )
    } else {
        //...
    }
    console.log("Login successful")
    res.status(200).end()
})
.catch(error => {
    console.log("Error logging in", error)
    res.status(400).end()
})

}

The JWT the server receives from the request must be send back to the client. How do I do this? I seem to be lost... Thanks!

Upvotes: 0

Views: 233

Answers (1)

Fluxium
Fluxium

Reputation: 110

Figured it out. I can just use res.status(200).end(dataFromServer). I knew it was something simple.

Upvotes: 0

Related Questions