What you'll build
- Sign-up and sign-in forms built on Server Actions
- The session token in an HTTP-only cookie, never in
localStorage - A Continue with Google button and a callback page
- A
getCurrentUser()helper and a working sign-out
Before you start
- Node.js 20 or newer
- A Next.js 16 app using the App Router (
npx create-next-app@latest) - A free CloudHike.dev account
How the login flow works
CloudHike Auth is a plain HTTP API. You send an email and password, and it answers with { token, user }. You keep the token and send it as authorization: Bearer <token> to ask who is signed in. It sets no cookies of its own, so where you keep the token is up to you.
In a Next.js app, the safest place is an HTTP-only cookie that your server sets. Page scripts can't read it, so an XSS bug can't steal the session. The browser sends it on every request, so Server Components, Server Actions and Route Handlers can all read it.
| Flow | Where the token comes from | Who sets the cookie |
|---|---|---|
| Email sign-up and sign-in | The sign-up/email or sign-in/email response | A Server Action |
The URL fragment (#token=...) after Google sends the user back | A Route Handler, called by a small client page |
Step 1: Deploy Auth and add your keys
- Sign in at cloudhike.dev and create a project.
- Click Deploy on the Auth card.
- Click Copy as .env and paste the values into
.env.local. AddAPP_URLyourself.
AUTH_URL=https://...
AUTH_PUBLISHABLE_KEY=...
AUTH_SECRET_KEY=...
# Your app's own address, used for the Google return link
APP_URL=http://localhost:3000AUTH_URL and AUTH_PUBLISHABLE_KEY are safe in browser code, but this guide only uses them on the server. AUTH_SECRET_KEY unlocks admin endpoints and must never leave the server. You won't need it here. See Deploy for what each one does.
npm install server-onlyStep 2: Write a server-only auth helper
Put every call to the Auth API in one file. Each request sends your publishable key as x-api-key. Errors come back as { message } with a status code, so turn those into a typed error your forms can show.
import "server-only";
import { cookies } from "next/headers";
const AUTH_URL = process.env.AUTH_URL!;
const baseHeaders = {
"content-type": "application/json",
"x-api-key": process.env.AUTH_PUBLISHABLE_KEY!,
};
export const SESSION_COOKIE = "session";
export type User = { id: string; email: string; name: string };
export type Session = { user: User } | null;
export class AuthError extends Error {
constructor(message: string, public status: number) {
super(message);
}
}
async function call<T>(path: string, init: RequestInit = {}): Promise<T> {
const res = await fetch(`${AUTH_URL}${path}`, {
...init,
headers: { ...baseHeaders, ...init.headers },
cache: "no-store",
});
if (!res.ok) {
const { message } = await res.json().catch(() => ({ message: res.statusText }));
throw new AuthError(message ?? "Auth request failed", res.status);
}
return res.json() as Promise<T>;
}
export function signUpWithEmail(name: string, email: string, password: string) {
return call<{ token: string; user: User }>("/sign-up/email", {
method: "POST",
body: JSON.stringify({ name, email, password }),
});
}
export function signInWithEmail(email: string, password: string) {
return call<{ token: string; user: User }>("/sign-in/email", {
method: "POST",
body: JSON.stringify({ email, password }),
});
}
// Returns the session and user, or null when the token is missing or invalid.
export async function getSession(token: string | undefined): Promise<Session> {
if (!token) return null;
try {
return await call<Session>("/get-session", {
headers: { authorization: `Bearer ${token}` },
});
} catch (err) {
if (err instanceof AuthError && err.status === 401) return null;
throw err; // a real outage: don't silently sign everyone out
}
}
// Ends the session at the Auth API. Failures are logged, not thrown:
// the caller deletes the cookie either way.
export async function signOutToken(token: string) {
try {
const res = await fetch(`${AUTH_URL}/sign-out`, {
method: "POST",
headers: { ...baseHeaders, authorization: `Bearer ${token}` },
});
if (!res.ok) console.error("Sign-out failed", res.status);
} catch (err) {
console.error(err);
}
}
// --- Cookie helpers. Call these only in Server Actions and Route Handlers. ---
export async function setSessionCookie(token: string) {
(await cookies()).set(SESSION_COOKIE, token, {
httpOnly: true, // page scripts can't read it
secure: process.env.NODE_ENV === "production",
sameSite: "lax", // sent on normal navigations, not on cross-site POSTs
path: "/",
maxAge: 60 * 60 * 24 * 7, // a week; getSession() stays the real check
});
}
export async function clearSessionCookie() {
(await cookies()).delete(SESSION_COOKIE);
}
export async function getCurrentUser() {
const token = (await cookies()).get(SESSION_COOKIE)?.value;
const session = await getSession(token);
return session?.user ?? null;
}The cookie's maxAge only controls how long the browser keeps it. Whether the session is still valid is decided by get-session on every request, so a signed-out or expired token is rejected even if the cookie is still there.
Step 3: Sign up and sign in with a Server Action
Both forms share one action file. The action calls the Auth API, sets the cookie, then redirects. Call redirect() outside the try block: it works by throwing, and a catch would swallow it.
"use server";
import { redirect } from "next/navigation";
import { AuthError, setSessionCookie, signInWithEmail, signUpWithEmail } from "@/lib/auth";
export type FormState = { error: string } | null;
const isEmail = (s: string) => /^\S+@\S+\.\S+$/.test(s);
export async function signUp(_prev: FormState, form: FormData): Promise<FormState> {
const name = String(form.get("name") ?? "").trim();
const email = String(form.get("email") ?? "").trim().toLowerCase();
const password = String(form.get("password") ?? "");
if (!name || !isEmail(email)) return { error: "Enter your name and a valid email." };
if (password.length < 8) return { error: "Use a password of at least 8 characters." };
try {
const { token } = await signUpWithEmail(name, email, password);
await setSessionCookie(token);
} catch (err) {
if (err instanceof AuthError) return { error: err.message };
console.error(err);
return { error: "Something went wrong. Please try again." };
}
redirect("/dashboard");
}
export async function signIn(_prev: FormState, form: FormData): Promise<FormState> {
const email = String(form.get("email") ?? "").trim().toLowerCase();
const password = String(form.get("password") ?? "");
if (!isEmail(email) || !password) return { error: "Enter your email and password." };
try {
const { token } = await signInWithEmail(email, password);
await setSessionCookie(token);
} catch (err) {
if (err instanceof AuthError && err.status === 403) {
return { error: "Please confirm your email first. Check your inbox for the link." };
}
if (err instanceof AuthError && err.status < 500) {
return { error: "Wrong email or password." };
}
console.error(err);
return { error: "Sign-in is unavailable right now. Please try again." };
}
redirect("/dashboard");
}A 403 on sign-in means Require a verified email is on and the user hasn't opened the link yet. The email and password docs explain the option, and Password Reset and Email Verification builds the rest of that flow.
"use client";
import { useActionState } from "react";
import { signIn } from "../actions";
export function LoginForm() {
const [state, action, pending] = useActionState(signIn, null);
return (
<form action={action} className="grid gap-3">
<input name="email" type="email" autoComplete="email" placeholder="you@example.com" required />
<input name="password" type="password" autoComplete="current-password" placeholder="Password" required />
<button disabled={pending}>{pending ? "Signing in…" : "Sign in"}</button>
{state?.error && <p role="alert">{state.error}</p>}
</form>
);
}The sign-up form is the same with a name field, autoComplete="new-password", minLength={8} and the signUp action. The login page puts the form and the Google button (Step 4) together:
import Link from "next/link";
import { GoogleButton } from "../google-button";
import { LoginForm } from "./login-form";
export default function LoginPage() {
return (
<main className="mx-auto grid max-w-sm gap-4 p-8">
<h1>Sign in</h1>
<GoogleButton />
<p>or</p>
<LoginForm />
<p>
New here? <Link href="/signup">Create an account</Link>
</p>
</main>
);
}Step 4: Add Continue with Google
First, turn Google on. On the Auth card, open Sign in with GitHub or Google. Pick Shared to use CloudHike's OAuth app while you build, or Your own with a client ID and secret from Google Cloud. Then add http://localhost:3000 (and later your real domain) under Sites users can return to. Users are only sent back to sites on that list. The social sign-in docs have the details.
The flow is a page navigation. Your button links to {AUTH_URL}/social/google?to=<return URL>. After Google, the user lands on the return URL with the token in the fragment: #token=..., or #error=... if they cancelled. The fragment is never sent to any server, which keeps the token out of logs. That also means your server can't see it, so a small client page has to pick it up.
// A Server Component: it builds the link on the server, so no env vars reach the browser.
export function GoogleButton() {
const returnTo = new URL("/auth/callback", process.env.APP_URL).toString();
const href = `${process.env.AUTH_URL}/social/google?to=${encodeURIComponent(returnTo)}`;
return <a href={href}>Continue with Google</a>;
}The callback page reads the fragment, clears it from the address bar right away, and posts the token to your own Route Handler:
"use client";
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
export default function AuthCallbackPage() {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
const started = useRef(false);
useEffect(() => {
if (started.current) return; // React may run effects twice in development
started.current = true;
const params = new URLSearchParams(window.location.hash.slice(1));
const token = params.get("token");
const failed = params.get("error");
// Remove the token from the address bar and history.
window.history.replaceState(null, "", window.location.pathname);
if (!token) {
setError(failed ? "Google sign-in was not completed." : "No sign-in token was found.");
return;
}
fetch("/api/auth/session", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ token }),
})
.then((res) => {
if (!res.ok) throw new Error();
router.replace("/dashboard");
router.refresh();
})
.catch(() => setError("Could not finish signing in. Please try again."));
}, [router]);
return (
<main className="p-8">
{error ? (
<p role="alert">
{error} <Link href="/login">Back to sign in</Link>
</p>
) : (
<p>Signing you in…</p>
)}
</main>
);
}The Route Handler checks the token with get-session before it sets the cookie, so a made-up token is never stored. It also checks the Origin header, so another site can't post its own token and sign your visitor into the wrong account.
import { getSession, setSessionCookie } from "@/lib/auth";
export async function POST(request: Request) {
const origin = request.headers.get("origin");
if (origin !== new URL(process.env.APP_URL!).origin) {
return Response.json({ message: "Bad origin" }, { status: 403 });
}
const body = await request.json().catch(() => null);
const token = typeof body?.token === "string" ? body.token : "";
try {
const session = await getSession(token);
if (!session) return Response.json({ message: "Invalid token" }, { status: 401 });
await setSessionCookie(token);
return Response.json({ ok: true });
} catch (err) {
console.error(err);
return Response.json({ message: "Auth is unavailable" }, { status: 503 });
}
}Don't call POST {AUTH_URL}/sign-in/social from code. Social sign-in only works as a browser navigation to /social/google, and the API refuses the POST.
Step 5: Show the current user and sign out
Any Server Component can now ask who is signed in. Wrap the part that reads cookies in <Suspense>, so the rest of the page can stream first.
import { Suspense } from "react";
import { redirect } from "next/navigation";
import { getCurrentUser } from "@/lib/auth";
import { signOut } from "./actions";
async function Welcome() {
const user = await getCurrentUser();
if (!user) redirect("/login");
return (
<>
<p>Signed in as {user.email}</p>
<form action={signOut}>
<button>Sign out</button>
</form>
</>
);
}
export default function DashboardPage() {
return (
<main className="p-8">
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading…</p>}>
<Welcome />
</Suspense>
</main>
);
}Sign-out ends the session at the Auth API, then deletes the cookie. Even if the API call fails, the cookie is gone, so the browser is signed out.
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { clearSessionCookie, SESSION_COOKIE, signOutToken } from "@/lib/auth";
export async function signOut() {
const token = (await cookies()).get(SESSION_COOKIE)?.value;
if (token) await signOutToken(token);
await clearSessionCookie();
redirect("/login");
}Checking the user in each page works, but it is easy to forget one. Protect Routes and Server Actions in Next.js 16 moves this into a Data Access Layer with a proxy.ts redirect in front of it.
Production checklist
- Add
AUTH_URL,AUTH_PUBLISHABLE_KEYandAPP_URLto your host's environment variables. SetAPP_URLto your realhttps://domain. - Add your production domain under Sites users can return to, or Google sign-in can't send users back.
- Switch Google to Your own OAuth credentials before launch, so the consent screen shows your app's name.
- Check that the cookie is
Securein production (it is whenNODE_ENVisproduction) and that your site is served over HTTPS. - Protect sign-up and sign-in from brute force with a Redis rate limit.
- Never put
AUTH_SECRET_KEYin a Client Component or aNEXT_PUBLIC_variable. If it leaks, click Reset keys on the Auth card; users stay signed in.
Auth is billed by monthly active users. See pricing for what each plan includes.
Frequently asked questions
Where should I store the auth token in Next.js?
In an HTTP-only, Secure, SameSite=Lax cookie that your server sets from a Server Action or Route Handler. Page scripts can't read it, so it can't be stolen by an XSS bug the way a token in localStorage can.
Can I set a cookie from a Next.js Server Component?
No. Cookies are set with a Set-Cookie response header, and a Server Component may already be streaming when it runs. Set and delete cookies in a Server Action or a Route Handler. Server Components can read them.
Why is the Google token in the URL fragment instead of the query string?
Browsers never send the fragment (the part after #) to any server. That keeps the token out of server logs, proxies and Referer headers. A client page reads it and hands it to your own server.
Do I need NextAuth or Auth.js for this?
No. CloudHike Auth stores users and sessions and runs the Google OAuth flow for you. Your app only calls a few HTTP endpoints and keeps the token in a cookie.
How do I add GitHub login too?
Turn GitHub on in the same Sign in with GitHub or Google panel, then add a second link to AUTH_URL/social/github with the same to parameter. The callback page and Route Handler work unchanged.
