The best way to use google sheets API in Next.js App Dir
Unanswered
American black bear posted this in #help-forum
American black bearOP
Is it safe to initialize google sheets api functions inside lib folder?
8 Replies
American black bearOP
export const initializeSheets = async () => {
const auth = await getAuth();
return google.sheets({ version: "v4", auth });
};
export const getSheetData = async ({}: {}) => {
try {
const sheets = await initializeSheets();
const range = "A:E";
const response = await sheets.spreadsheets.values.get({
spreadsheetId: GOOGLE_SHEET_ID_OF_DATA as string,
range,
});
const rows = response.data.values;
if (rows?.length) {
return rows;
} else {
return [];
}
} catch (err: any) {
console.error("The API returned an error:", err.message);
return [];
}
};export const updateFormValues = async ({
request,
spreadsheetId = GOOGLE_SHEET_ID as string,
callAppsScript = true,
appScriptData = {},
}: {
request: any;
spreadsheetId?: string;
callAppsScript?: boolean;
appScriptData?: object;
}) => {
const sheets = await initializeSheets();
const rangeValues = [
{ range: "Form!C5", value: request.unitId ?? "N/A" },
{ range: "Form!F5", value: request.noOfQuestions ?? "N/A" },
{ range: "Form!C7", value: request.childOrder ?? "N/A" },
{ range: "Form!F7", value: request.correctAnswerScore ?? "N/A" },
{ range: "Form!C9", value: request.topicId ?? "N/A" },
{ range: "Form!F9", value: request.wrongAnswerScore ?? "N/A" },
{ range: "Form!C11", value: request.duration ?? "N/A" },
{ range: "Form!F11", value: request.totalScore ?? "N/A" },
{ range: "Form!C13", value: request.title ?? "N/A" },
{ range: "Form!F13", value: request.passPercentage ?? "N/A" },
{ range: "Form!C15", value: request.sheetName ?? "N/A" },
{ range: "Form!F15", value: request.cheatSheetContent ?? "N/A" },
{ range: "Form!C17", value: request.resourceId ?? "N/A" },
];
try {
const requests = rangeValues.map(({ range, value }) => ({
range: range,
values: [[value]],
}));
const batchUpdateRequest = {
data: requests,
valueInputOption: "RAW",
};
const response = await sheets.spreadsheets.values.batchUpdate({
spreadsheetId: spreadsheetId,
requestBody: batchUpdateRequest,
});
if (callAppsScript) {
const appScriptRes = await callAppsScriptFunction(appScriptData);
console.log(appScriptRes, "appScriptRes");
return { response, appScriptRes };
} else {
return { response };
}
} catch (err: any) {
console.error("The API returned an error:", err.message);
return { error: err.message };
}
};I have these functions initialized in
lib/google-api.ts file, and I use these functions inside API routes and server components.In
getSheetData & updateFormValues I have initialized sheets at every call, is this the good way to do it? I will have very frequent calls to these functions.American black bearOP
Bump 

American black bearOP
ugh
American black bearOP
ahmm, I even switched from next.js to frontend plain react, still now answeeer
American black bearOP