#Cookie not being set

3 messages · Page 1 of 1 (latest)

midnight holly
#
import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { setCookie } from 'cookies-next';

export async function GET(req) {
  const searchParams = req.nextUrl.searchParams;
  const code = searchParams.get('code');
  console.log(code);

  if (!code) {
    return new NextResponse(
      JSON.stringify(
        { error: 'No code provided' },
        { status: 400 },
        { headers: {
            'Content-Type': 'application/json'
        } }
      )
    );
  }

  try {
    const params = new URLSearchParams();
    params.append('client_id', process.env.CLIENT_ID);
    params.append('client_secret', process.env.CLIENT_SECRET);
    params.append('grant_type', 'authorization_code');
    params.append('code', code);
    params.append('redirect_uri', `${process.env.URL_REDIRECT}/api/auth/callback`);

    const response = await fetch('https://discord.com/api/oauth2/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: params
    })
    .then(res => res.json())
    .catch(err => console.error(err));

    const { access_token } = response;
console.log(access_token)
    return new NextResponse(
      JSON.stringify(
        { token: access_token },
        { status: 200 },
        { headers: {
            'Content-Type': 'application/json',
            'Set-Cookie': `access_token=${access_token}; Max-Age=86400; SameSite=Lax`
        } }
      )
    )
  } catch (error) {
    return new NextResponse(
      JSON.stringify(
        { error: `Error in code: ${error}` },
        { status: 500 },
        { headers: {
            'Content-Type': 'application/json'
        } }
      )
    );
  }
}

The cookie isn't being set when i visit my browser Application -> cookies
Plz help

civic raptorBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

midnight holly
#

Prblm fixed.
Once again used setCookie from cookies-next and with some edits in it -

initialized a var to new NextResponse() and then passed it to the req of setCookie

it worked.