Closed4
better-authでServer Actionsを使ったサインインがしたい!

ドキュメント確認。
とりあえずソーシャルアカウントでサインインしたいので、Signin with social providersを見ると、authClientをsrc/libらへんに置いてそこからAPIを呼び出して使うやりかたが紹介されている。
Next.jsなのでせっかくならAuth.jsのようにserver actionsでサインインしたいところ。

よく見たら、email & passwordのサーバーサイドの例も書いてあった。(目節穴)
auth.api.~
でサーバーサイドからAPIを叩けそう。
とりあえずbetter-authをprisma(sqlite) + GitHubでセットアップ。
試しにServer Actionsを作成してみる。
src/actions/sign-in.ts
"use server";
import { auth } from "@/lib/auth";
export const signIn = async () => {
const res = await auth.api.signInSocial({
body: {
provider: "github",
},
});
console.log(res);
};
実行したら、こんな出力が出た。
{
url: 'https://github.com/login/oauth/authorize?<編集済>
redirect: true
}
このままredirectしたら良さげ。

とりあえずurlが得られなかったときのURLは適当だけど、書いてみた。
src/actions/sign-in.ts
"use server";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
export const signIn = async () => {
const res = await auth.api.signInSocial({
body: {
provider: "github",
},
});
return redirect(res.url ?? "/");
};

正しくセッションが取得できた。GG
このスクラップは6ヶ月前にクローズされました