I have defined this server action that I want to trigger to exchange the code for an access token in a /app/auth/page.tsx where the page.tsx is a Client Component(‘use client’).
Server action:
'use server'
import { NextResponse } from "next/server"
import { cookies } from "next/headers"
export const authUser = async (code: string) => {
try {
const res = await fetch('https://api.notion.com/v1/oauth/token', {
method: 'POST',
headers: new Headers({
"Content-Type": 'application/json',
Authorization: `Basic ${Buffer.from(`${process.env.OAUTH_ID}:${process.env.CLIENT_SECRET}`).toString('base64')}`,
}), body: JSON.stringify({
grant_type: 'authorization_code',
code: code,
redirect_uri: 'http://localhost:3000/auth'
})
})
const responseData = await res.json();
cookies().set('accessToken', `${responseData.access_token}`, {secure: true, httpOnly: true})
} catch (err) {
return new Response(JSON.stringify({error: 'Failed to process request', details: err}), {
status: 500,
headers: {
'Content-Type': 'application/json'
}
})
}
}
Client Component:
"use client";
import React, { useEffect } from "react";
import { useSearchParams } from "next/navigation";
import { authUser } from "@/actions/auth";
const AuthPage: React.FC = () => {
const searchParams = useSearchParams();
const code = searchParams.get("code");
useEffect(() => {
if (code) {
authUser(code);
}
}, [code]);
return (
<div>
<h2>Loading...</h2>
</div>
);
};
export default AuthPage;
Questions:
- Is this approach right?
- Should I define an API route to handle the exchange?
- What should have I done different?
The goal is to get the access_token from Notion Oauth and to set it in a cookie. For the moment the cookie value is undefined, idk why is this happening.
I try to handle this with server action as a way of learning my way through the new Next.js 13++ and I am not sure I did the right thing.
In my process of learning I avoid libraries like NextAuth to better understand what is going on, after that I am open to using this tools.
Rares Ciubotaru is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.