Kilan Van Loo
Kilan Van Loo

Reputation: 23

Can you chain call server actions in Next.js?

Problem

To simplify, here's the necessary code to highlight my problem:

Update profile:

// pages/api/update-profile.js
import { apiRequest } from '../utils/apiRequest';

export default async function handler(req, res) {

  try {
    const { name, email } = req.body;
    await apiRequest('/api/profile', 'PUT', { name, email });

  } catch (error) {
    res.status(500).json({ message: 'Error updating profile', error: error.message });
  }
}

Make api requests:

"server only";

// utils/apiRequest.js
export async function apiRequest(url, method, data = null) {
  try {
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getAccessToken()}`,
      },
      body: data ? JSON.stringify(data) : null,
    });

    if (response.status === 401) {
      // Token has expired, try to refresh it
      const newAccessToken = await refreshAccessToken();
      if (newAccessToken) {
        // Try the request again with the new token
        return apiRequest(url, method, data);
      } else {
        // Couldn't refresh the token, return the original 401 response
        return response;
      }
    }

    return response;
  } catch (error) {
    throw error;
  }
}

async function refreshAccessToken() {
  try {
    // Get refresh token from cookies 
    const refreshToken = await getRefreshToken();
    // Make another apiRequest to get a new access token 
    const accessToken = await apiRequest('/access-token', "POST", refreshToken)
    
    // Here I store the access token using "next/headers"
    await setServerCookies("access", accessToken)

    return newAccessToken;
  } catch (error) {
    // Failed to refresh the token
    return null;
  }
}

I now get the following error:

Error: Cookies can only be modified in a Server Action or Route Handler.

I think this error is because, although the initial apiRequest was made from a server action, the chain of api request calls is no longer seen as a Server Action.

Question

How can I chain call server actions?

Upvotes: 0

Views: 20

Answers (0)

Related Questions