最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

next.js - {"error":"Failed to authenticate with Google"} - 500 error in production only - St

programmeradmin2浏览0评论

I have the below set up to try and get users data from google calendar and tasks APIs.

Googleauth.ts

import { google } from 'googleapis';
import { NextApiRequest, NextApiResponse } from 'next';

const oauth2Client = new google.auth.OAuth2(
  process.env.GOOGLE_CLIENT_ID,   
  process.env.GOOGLE_CLIENT_SECRET, 
  process.env.GOOGLE_REDIRECT_URI 
);

const SCOPES = [
  '.readonly',
  '.readonly',
];

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    if (req.method === 'GET') {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
      res.setHeader('Access-Control-Allow-Credentials', 'true');

      // Generate the authorization URL
      const authUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline', 
        response_type: 'token',
        prompt: 'consent',
        scope: SCOPES,
        include_granted_scopes:true,
      });
      // Redirect the user to Google's OAuth page
      res.redirect(authUrl);
    } else {
      res.status(405).json({ error: 'Method Not Allowed' });
    }
  } catch (error) {
    console.error('Error during Google OAuth:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

callback.ts

import { google } from 'googleapis';
import { NextApiRequest, NextApiResponse } from 'next';
import cookie from 'cookie';

const oauth2Client = new google.auth.OAuth2(
  process.env.GOOGLE_CLIENT_ID,
  process.env.GOOGLE_CLIENT_SECRET,
  process.env.GOOGLE_REDIRECT_URI
);
console.log('Using redirect URI:', process.env.GOOGLE_REDIRECT_URI);

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { code } = req.query;
  console.log('Received authorization code:', code, req,res);
  if (!code) {
    return res.status(400).json({ error: 'Code is missing from the query' });
  }

  try {
    // Exchange the code for tokens
    const { tokens } = await oauth2Client.getToken(code as string);
    oauth2Client.setCredentials(tokens);
    
    // Set the access token in an HttpOnly cookie
    res.setHeader(
      'Set-Cookie',
      cookie.serialize('access_token', tokens.access_token as string, {
        httpOnly: false,
        secure: process.env.NODE_ENV === 'production', // Use secure cookies in production
        maxAge: 3600, // 1 hour
        path: '/',
        sameSite: 'strict', 
      })
    );

    // Redirect to the homepage or wherever you want to display the calendar
    res.redirect('/');  // Redirects to home after successful authentication
  }  catch (error: any) {
    console.error('OAuth Error:', error.response?.data || error.message);
    res.status(500).json({ error: error.response?.data || 'Failed to authenticate with Google' });
  }
}

Everything works fine locally but not in production. I have my project set up in Netlify, all the environment variables set up properly there, but still getting the same error over and over again.

My app has also been authorised by Google.

Anyone knows if my set up is correct? Or something missing?

Thank you

发布评论

评论列表(0)

  1. 暂无评论