Cookie not being set
Answered
NanotechPikachu posted this in #help-forum
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
Answered by NanotechPikachu
Prblm fixed.
Once again used
it worked.
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.
1 Reply
Prblm fixed.
Once again used
it worked.
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.
Answer