Server Action or API in next.js app router?
Unanswered
English Lop posted this in #help-forum
English LopOP
I am trying to create an API endpoint using this code as an example. I want to use Next.js App router. Do I use api endpoint or server actions? A bit confused. I am using auth.js for authentication. Here is the sample code I want to use:
});
app.get("/sso/metabase", restrict, (req, res) => {
const ssoUrl = new URL("/auth/sso", METABASE_SITE_URL);
ssoUrl.searchParams.set("jwt", signUserToken(req.session.user));
ssoUrl.searchParams.set("return_to", req.query.return_to ?? "/");
res.redirect(ssoUrl);});
15 Replies
@English Lop I am trying to create an API endpoint using this code as an example. I want to use Next.js App router. Do I use api endpoint or server actions? A bit confused. I am using auth.js for authentication. Here is the sample code I want to use:
app.get("/sso/metabase", restrict, (req, res) => {
const ssoUrl = new URL("/auth/sso", METABASE_SITE_URL);
ssoUrl.searchParams.set("jwt", signUserToken(req.session.user));
ssoUrl.searchParams.set("return_to", req.query.return_to ?? "/");
res.redirect(ssoUrl);
});
for auth.js you should use a route handler. Route handlers are defined like this:
export async function GET() {
// YOUR CODE
const res = await fetch('https://data.mongodb-api.com/...', {
headers: {
'Content-Type': 'application/json',
'API-Key': process.env.DATA_API_KEY,
},
})
const data = await res.json()
return Response.json({ data })
}The most difference between route handlers and server actions are:
Route handlers are the common api routes and server actions are just functions that will be compiled as api endpoints. Their purpose is to use them inside client component for doing server mutations on the server.
Keep in mind, that auth.js and next-auth@beta are pretty buggy. I recommend you to use next-auth@14
Route handlers are the common api routes and server actions are just functions that will be compiled as api endpoints. Their purpose is to use them inside client component for doing server mutations on the server.
Keep in mind, that auth.js and next-auth@beta are pretty buggy. I recommend you to use next-auth@14
English LopOP
Thanks for your replu. I'm auth.js v5. I first want to check if the user is authenticated and then direct them to metabase to sign in using a jwt token and then redirect back to the req page.
I think i can use const session = auth()
import { NextResponse } from "next/server";
import jwt from "jsonwebtoken";
import { auth } from "@/auth";
// Environment variables for Metabase configuration
const METABASE_SITE_URL = process.env.METABASE_SITE_URL;
const METABASE_JWT_SHARED_SECRET = process.env.METABASE_JWT_SHARED_SECRET;
// Function to sign the user token
function signUserToken(user) {
const [firstName, ...lastNameParts] = user.name.split(" ");
const lastName = lastNameParts.join(" ") || "";
const payload = {
email: user.email,
first_name: firstName,
last_name: lastName
// Add any additional claims needed for your Metabase setup
};
const token = jwt.sign(payload, METABASE_JWT_SHARED_SECRET, { algorithm: "HS256" });
return token;
}
// Restrict middleware to ensure user is authenticated
async function restrict() {
const session = await auth()
const user = session?.user; // Replace with your session/user auth logic
if (!user) {
return false; // User is not authenticated
}
return user;
}
// GET handler for /api/sso/metabase
export async function GET(req) {
// Check if the user is authenticated
const user = restrict()
if (!user) {
const loginUrl = new URL("/login", req.nextUrl.origin);
loginUrl.searchParams.set("return_to", req.nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
// Create Metabase SSO URL
const ssoUrl = new URL("/auth/sso", METABASE_SITE_URL);
ssoUrl.searchParams.set("jwt", signUserToken(user));
ssoUrl.searchParams.set("return_to", req.nextUrl.searchParams.get("return_to") || "/");
// Redirect to Metabase
return NextResponse.redirect(ssoUrl);
}When Iv visit localhost:3000/api/sso/metabase, I get server can't handle request error
Burmese
Are you sure you have your route setup correctly in your api folder? You should have a route.ts file.
English LopOP
It's placed in: app/api/sso/metabase/route.ts
Burmese
Have you tried adding try/catch to see where the error is coming from?
English LopOP
Yes, I found the error. User was undefined
Is it a bad idea to use auth.js in production?
@English Lop Is it a bad idea to use auth.js in production?
yes. I heard many people that had problem with auth.js and next-auth@beta while developing. So keep that in mind, that you might come accross unsolvable issues
English LopOP
I set up auth.js auth with credentials and google providers, two factor auth, and email verification using auth.js beta. In development everything works fine. Maybe I don't have any issues because of my simple use case? Should I still be weary of using it in production? Sorry for all the questions. I'm newer dev.
@English Lop I set up auth.js auth with credentials and google providers, two factor auth, and email verification using auth.js beta. In development everything works fine. Maybe I don't have any issues because of my simple use case? Should I still be weary of using it in production? Sorry for all the questions. I'm newer dev.
I wouldn't use it. You can have a different mind and that's completely fine