Ploy
Ploy
Authentication

Authentication

Add managed sign-in with email and password, email sign-in links, passkeys, and Google, Apple, or GitHub to your applications with Ploy Auth.

Authentication

Ploy Auth gives your app its own user accounts and sessions without running an auth server. Users are stored in one of your databases, and Ploy serves the sign-in endpoints on your app's own domain under /_ploy/auth/*. Your application tables can share that database and reference ploy_users(id) with real foreign keys; see sharing the auth database.

Users can sign in with:

MethodDefaultConfigure in
Email and passwordOnDashboard → Auth → Sign-in methods
Sign-in link (magic link)OffDashboard → Auth → Sign-in methods, with email
Sign-in code (email code)OffDashboard → Auth → Sign-in methods, with email
PasskeysOffDashboard → Auth → Sign-in methods
GoogleOffDashboard, with your Google OAuth client
AppleOffDashboard, with your Sign in with Apple key
GitHubOffDashboard, with your GitHub OAuth App

Every method can be turned on or off per project. See Social sign-in and Passkeys for provider setup, Emails, sign-in links and passwords for the emails Ploy Auth sends, Users and data for how accounts are stored and how to reference them from your own tables, and Hooks to run your own code on sign-up, sign-in and other account events.

Enable auth

Add an auth binding to your ploy.yaml:

ploy.yaml
kind: dynamic
build: pnpm build
out: dist
auth:
  binding: AUTH_DB

On the next production deployment Ploy:

  1. Finds the project's existing auth database or creates a new project-specific database and binds it to your worker as AUTH_DB. New projects do not share auth databases merely because they use the same binding name.
  2. Creates the auth tables (ploy_users, ploy_sessions, ploy_identities, ploy_passkeys, ploy_tokens) in that database.
  3. Generates a per-project secret for signing session tokens. It is encrypted at rest and never exposed to your code.
  4. Serves the auth endpoints at /_ploy/auth/* and adds the PLOY_AUTH binding for server-side checks.

Auth becomes available only after its database schema is ready. New production setups start with sign-up closed. Enable Allow sign-ups in the dashboard, or explicitly seed the initial settings in ploy.yaml:

auth:
  binding: AUTH_DB
  allow_signups: true
  require_email_verification: true

Email verification is required by default for new setups; set require_email_verification: false to opt out. These options only seed a new setup. Redeploying does not overwrite settings you changed in the dashboard. Requiring email verification also needs configured auth email.

Preview deployments use the project's production auth database, users, sessions, and sign-in settings by default. Only trusted repository branches may deploy; opening a pull request from a fork does not deploy its code. Owners and admins can turn off Enable on previews under Auth → Settings. Auth endpoints enforce the setting on each request; redeploy previews to update their database bindings. Preview deployments never provision auth or apply database migrations. Deploy production first to initialize auth. OAuth providers still need callback URLs registered for each preview origin.

Configure sign-in methods

Open Auth in the dashboard and select your project. The Settings tab has:

SettingDescription
Email and passwordAllow sign-up and sign-in with a password.
Magic linkAllow sign-in, and sign-up when allowed, with a one-time link sent by email. Needs email enabled for the organization. See Sign-in links.
Email codeAllow sign-in, and sign-up when allowed, with a 6-digit code sent by email. Needs email enabled for the organization. See Sign-in codes.
PasskeysAllow sign-up and sign-in with Face ID, Touch ID, Windows Hello, or a security key.
Google, Apple, GitHubEnter the provider credentials, then turn the provider on. Each shows the callback URL to register.
Allow sign-upsWhen off, only existing users can sign in, with any method.
Require namePassword and passkey sign-ups must send metadata.name.
Allow plus addressesOff by default: new accounts cannot use addresses with a + tag, such as name+tag@example.com. Existing accounts still sign in.
Block disposable emailsOn by default: new accounts cannot use disposable or forwarding email providers, such as mailinator.com or duck.com, or their subdomains. Existing accounts still sign in.
SessionsSession lifetime, extending active sessions, maximum session age, and the session cookie cache. See Sessions.
Share sessionsSign users in once across a verified custom domain's subdomains. Off by default. See Sessions across subdomains.
EmailsRequire email verification, and the address auth emails are sent from. See Emails, sign-in links and passwords.
Email templatesChange the subject and text of each auth email. See Email templates.

Changes take effect on the next request; no redeploy is needed. At least one sign-in method must stay on.

Only organization owners and admins can change sign-in methods or provider credentials. Provider secrets are write-only: the dashboard shows whether one is saved, never its value.

Endpoints

All endpoints are served on your app's domain at /_ploy/auth/* and use the ploy_session cookie.

EndpointMethodDescription
/configGETEnabled sign-in methods, for building your own UI
/signupPOSTCreate an account with email and password
/signinPOSTSign in with email and password
/oauth/{provider}GETStart Google, Apple, or GitHub sign-in (browser navigation)
/callback/{provider}GET, POSTProvider redirect target; register it with the provider
/passkey/register/optionsPOSTStart passkey sign-up, or add a passkey when signed in
/passkey/register/verifyPOSTFinish passkey registration
/passkey/login/optionsPOSTStart passkey sign-in
/passkey/login/verifyPOSTFinish passkey sign-in
/passkeysGETList the signed-in user's passkeys
/passkeys/{id}DELETERemove one of the signed-in user's passkeys
/meGETThe current user
/signoutPOSTRevoke the current session
/email/verify/requestPOSTSend the verification email again
/email/verifyGETVerification link target
/email/verify/continuePOSTSign in the waiting sign-up browser once verified
/password/forgotPOSTEmail a password reset link
/password/resetPOSTSet a new password with a reset token
/password/changePOSTChange or set the signed-in user's password
/magic-linkPOSTEmail a sign-in link
/magic-link/verifyGET, POSTSign-in link target: confirm page, then sign in
/email-codePOSTEmail a sign-in code
/email-code/verifyPOSTSign in with an emailed code

See Emails, sign-in links and passwords for the email endpoints, password changes, and the hosted reset pages.

Errors are JSON with a human-readable error and a stable code:

{
	"error": "Invalid credentials",
	"message": "Invalid credentials",
	"code": "invalid_credentials"
}

Email and password

const response = await fetch("/_ploy/auth/signup", {
	method: "POST",
	credentials: "include",
	headers: { "Content-Type": "application/json" },
	body: JSON.stringify({
		email: "user@example.com",
		password: "securepassword123",
		metadata: { name: "Jane Doe" }, // optional, up to 1 KB
	}),
});

const { user } = await response.json();
// The ploy_session cookie is now set

/signin takes { email, password } and returns { user } the same way. Emails are trimmed and lowercased.

When email verification is required, /signup responds with { user, emailVerificationRequired: true } and no cookie, and /signin fails with code email_not_verified until the user opens the link in their verification email.

Social sign-in

Social sign-in is a full-page redirect. Send the browser to the provider endpoint with the page to return to:

window.location.href =
	"/_ploy/auth/oauth/google?redirectTo=" + encodeURIComponent("/dashboard");

After the provider confirms the user, they land on redirectTo with a session cookie. If sign-in fails, they land there with a ploy_auth_error query parameter instead. redirectTo must be a path or a URL on the same origin, or a sibling origin on the same scheme and port when sessions are shared; anything else falls back to /.

Current user

const response = await fetch("/_ploy/auth/me", { credentials: "include" });
const { user } = await response.json();
interface PloyUser {
	id: string;
	email: string;
	emailVerified: boolean;
	hasPassword: boolean; // false for sign-in link, passkey, and social-only accounts
	createdAt: string;
	updatedAt: string;
	metadata: Record<string, unknown> | null;
}

Server-side authentication

Your worker gets a PLOY_AUTH binding. Pass it the session token from the ploy_session cookie or an Authorization: Bearer header:

app/api/protected/route.ts
import { getPloyContext } from "@meetploy/nextjs";

export async function GET(request: Request) {
	const token = request.headers
		.get("Cookie")
		?.match(/(?:^|;\s*)ploy_session=([^;]+)/)?.[1];
	if (!token) {
		return Response.json({ error: "Unauthorized" }, { status: 401 });
	}

	const { env } = getPloyContext();
	const user = await env.PLOY_AUTH.getUser(token);
	if (!user) {
		return Response.json({ error: "Unauthorized" }, { status: 401 });
	}

	return Response.json({ userId: user.id });
}
MethodReturns
getUser(token)The PloyUser, or null if the session is invalid
verifyToken(token)true if the session is valid and not revoked
getProviderToken(token, provider)The user's social provider access token for calling its API, or null
getSignInMethods(userIds)How each of up to 100 users can sign in: password, linked providers, and passkeys count

The session methods check the session against the database, so a signed-out or revoked session is rejected immediately.

getSignInMethods takes user IDs instead of a session, for screens such as an admin user list. It answers for any user of the project, so it is server-only: requests through /_ploy/auth are refused. Check that the caller is allowed to see other users before calling it. Unknown IDs are left out of the result.

const [methods] = await env.PLOY_AUTH.getSignInMethods([user.id]);
// { userId: "…", password: false, providers: ["github"], passkeys: 0 }

Sessions

  • Session tokens are signed with your project's secret and stored only as SHA-256 hashes, so a leaked database does not leak usable sessions.
  • The ploy_session cookie is HttpOnly, SameSite=Lax, and Secure on HTTPS.
  • Signing out revokes the session server-side, not just the cookie. Browser mutations reject untrusted Origin values with 403 invalid_origin, including same-site sibling attacks.
  • Sessions last 7 days by default and are extended while the user stays active. See Sessions.
  • Sessions belong to the host that started them, unless you share them across subdomains of a verified custom domain.

Built-in protection

Ploy Auth applies these limits to every project. Requests over a limit get 429 with a Retry-After header.

LimitDefault
Sign-up, password sign-in and change, passkey verification, sign-in link use, OAuth callbacks30 per 5 minutes per IP
OAuth starts and passkey challenges60 per 5 minutes per IP
Password sign-in and change attempts for one email address10 per 15 minutes
Verification, sign-in link, and reset emails3 per hour per address, 10 per hour per IP
/me and /signout600 per minute per IP

Also built in:

  • Password hashing with scrypt. See Users and data.
  • Uniform failures: a wrong password and an unknown email return the same 401 and take the same time.
  • CSRF-safe flows: OAuth uses state and PKCE (Google, GitHub); passkey challenges are single-use. Both are bound to a short-lived signed cookie.
  • No open redirects: redirectTo is restricted to your app's origin, or its sibling subdomains when sessions are shared.
  • Account takeover protection when linking providers by email. See Social sign-in.

Local development

ploy dev runs the same endpoints against a local SQLite database. Email and password, sign-in links, and passkeys work on localhost out of the box; emails land in the dev dashboard's local inbox. To try social sign-in locally, put the provider credentials in your project's .env; see Social sign-in.

Integrations

Pick the level of control you need:

OptionPackageBest for
Hosted pagesnoneAny framework, static sites, the fastest start: link to /_ploy/auth/sign-in
React components@meetploy/auth-reactDrop-in SignInForm, SignUpForm, UserButton, UserProfile inside your own pages
Next.js helpers@meetploy/nextjscurrentUser(), protect() and route middleware for the App Router
EndpointsnoneFully custom UI in any language

Starting fresh? Pick the Next.js with Auth template when creating a project in the dashboard, or copy one of the examples: nextjs-auth and vite-react-auth. Coming from another provider? See Migrating to Ploy Auth.

Next steps

How is this guide?

Last updated on