Search code examples
node.jsexpressnext.jscorsnext-connect

CORS error when trying to redirect from http://localhost:3000 to https://api.twitter.com in Next.js using next-connect?


I am trying to get redirect to work but always get bombarded with an error in console saying:

Access to fetch at 'https://api.twitter.com/oauth/authenticate?oauth_token=' (redirected from 'http://localhost:3000/api/auth/twitter/generate-auth-link') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I did see other answers on the same question & in fact, I just found I asked the same question exactly 2 months ago but that question works for opening up a pop-up window & does redirection in there & this one wants a redirection on the same page itself.

I also tried that same answer but it doesn't work & it still gives me cors error with this code:

.use((req, res, next) => {
    console.log('cors')
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    )
    if (req.method == 'OPTIONS') {
        res.setHeader('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET')
        return res.status(200).json({})
    }
    next()
})

I also tried using this code:

const allowedOrigins = ['http://localhost:3000']

const options: cors.CorsOptions = {
    allowedHeaders: [],
    origin: allowedOrigins,
}

.use(cors(options))

but that doesn't work either.

My oauth flow goes like this:

Click login on http://localhost:3000 → Go to https://api.twitter.com/oauth/authenticate?oauth_token=xxxx → Redirect back to http://localhost:3000

The code for the same oauth flow looks like this:

api/auth/twitter/generate-auth-link.ts

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

import handler from '@/server/api-route'
import { SERVER_URL, TWITTER_CONFIG } from '@/utils/index'
import { NextIronRequest } from '@/types/index'

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/auth/twitter/get-verifier-token`)

    req.session.twitter = {
        oauth_token,
        oauth_token_secret,
    }

    await req.session.save()

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

export default handler().get(generateAuthLink)

api/auth/twitter/get-verifier-token.ts

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

import handler from '@/server/api-route'
import { SERVER_URL, TWITTER_CONFIG } from '@/utils/index'
import { NextIronRequest } from '@/types/index'

const getVerifierToken = async (req: NextIronRequest, res: NextApiResponse) => {
    // check query params and session data
    const { oauth_token, oauth_verifier } = req.query

    if (typeof oauth_token !== 'string' || typeof oauth_verifier !== 'string') {
        res.status(401).send('Oops, it looks like you refused to log in..')
        return
    }

    if (!req.session.twitter)
        throw new Error("Can't find `oauth_token` & `oauth_token_secret` in `req.session.twitter`")

    const oauth_token_secret = req.session.twitter.oauth_token_secret

    if (typeof oauth_token_secret !== 'string') {
        res.status(401).send('Oops, it looks like your session has expired.. Try again!')
        return
    }

    // fetch the token / secret / account infos (from the temporary one)
    const { client, accessToken, accessSecret } = await new TwitterApi({
        appKey: TWITTER_CONFIG.consumerKey,
        appSecret: TWITTER_CONFIG.consumerSecret,
        accessToken: oauth_token,
        accessSecret: oauth_token_secret,
    }).login(oauth_verifier)

    const { name, screen_name, email } = await client.currentUser()

    req.session.twitter = { oauth_token: accessToken, oauth_token_secret: accessSecret }
    req.session.user = { name, screen_name, email }
    await req.session.save()

    res.redirect('/app')
}

export default handler().get(getVerifierToken)

How do I solve the cors issue so redirects work properly?

When I was using next-auth, it worked but can't figure out from it's code where it's happening. But I want the exact same flow. Click on Login & it gets redirected to Twitter API & when it's authenticated, get redirected back to localhost.


Solution

  • As mentioned here, Twitter API does not support CORS.

    So I couldn't just do res.redirect(url) in api/auth/twitter/generate-auth-link.ts so instead I sent the url back using res.send({ url }) & in the frontend I did the following:

    import ky from 'ky'
    
    const res: { url: string } = await ky.get('/api/auth/twitter/generate-auth-link').json()
    window.location.href = res.url
    

    And it worked!