4

I have a Link tag that looks like <Link href='/api/twitter/generate-auth-link'>Login with Twitter</Link>.

I have already created pages/api/twitter/generate-auth-link.ts that looks like:

import { NextApiResponse } from 'next'
import TwitterApi from 'twitter-api-v2'

import { TWITTER_CONFIG } from '../../../lib/config'
import { SERVER_URL } from '../../../utils/index'
import { NextIronRequest } from '../../../types/index'
import handler from '../../../server/api-route'

const generateAuthLink = async (
  req: NextIronRequest,
  res: NextApiResponse
) => {
  // Generate an authentication URL
  const { url, oauth_token, oauth_token_secret } = await new TwitterApi({
    appKey: TWITTER_CONFIG.consumerKey,
    appSecret: TWITTER_CONFIG.consumerSecret,
  }).generateAuthLink(`${SERVER_URL}api/twitter/get-verifier-token`, {linkMode:'authorize'})
  
  req.session.set(oauth_token, oauth_token_secret)
  await req.session.save()

  // redirect to the authentication URL
  res.redirect(url)
}

export default handler().get(generateAuthLink)

When I click on it, it throws the following error:

1 of 1 unhandled error

Unhandled Runtime Error
Error: Failed to load script: /_next/static/chunks/pages/api/twitter/generate-auth-link.js

Call Stack
HTMLScriptElement.script.onerror
node_modules/next/dist/client/route-loader.js (83:51)

How do I fix it?

Reproduction → https://github.com/deadcoder0904/twitter-api-v2-3-legged-login-using-next-connect

deadcoder0904
  • 7,232
  • 12
  • 66
  • 163
  • 1
    `Link` is used for page navigation, you should make a request (using `fetch` or `axios`) against that API route if you want to run it. – juliomalves Sep 26 '21 at 15:17
  • @juliomalves i get cors error then even though i have cors as a middleware. – deadcoder0904 Sep 27 '21 at 05:23
  • @deadcoder0904 Did you find a solution? I'm facing the exact same problem, just as you described, this only shows the error when I'm in my local env, once deployed the error is no longer showing – Josué Almonasi Nov 29 '21 at 20:02
  • @JosuéAlmonasi just use a `button` with a `fetch` instead of `Link` → https://github.com/deadcoder0904/twitter-api-v2-3-legged-login-using-next-connect/blob/main/components/Login.tsx#L20 – deadcoder0904 Dec 01 '21 at 05:03

0 Answers0