Next.js Discord

Discord Forum

The correct way to redirect from a POST request in App Router?

Unanswered
Airedale Terrier posted this in #help-forum
Open in Discord
Airedale TerrierOP
Hey folks!

I'm implementing "Sign in with Google" using the Google Identity Services (GIS) package and these docs: https://developers.google.com/identity/gsi/web/guides/overview

The TLDR is they provide a JS script and an HTML button. Once someone presses the button and authenticates successfully, GIS sends a POST request to URI that I give with the credential, csrf tokens etc.

At the end of the post request, I want to redirect the user to a different page and also set a session cookie. The following code works, but I'm wondering if there's a more "idiomatic" (correct) way of doing it?

I have tried using NextResponse.redirect() but it just hangs the backend.

I'm using Next.js 13.4.7 and the App directory.

export async function POST(request: NextRequest) {
        /* ... CSRF validation */

        /* ... save user to database etc */

    const response = new NextResponse(null, {
        status: 303,
    });
    response.headers.set("Location", new URL("/", request.url).href);
    response.cookies.set({
        name: "session",
        value: "abc123",
        sameSite: "lax",
        httpOnly: true,
        maxAge: 60 * 60,
    });

    return response;
}

0 Replies