---
title: "Inicia sesión desde una app de Node.js"
project: OpenAuth
version: 1.0
section: recipes
language: es
license: MIT
url: https://totaljs.es/docs/es/openauth/1-0/recipes/sign-in-nodejs/
updated: 2026-11-19T09:22:03.917Z
---

# Inicia sesión desde una app de Node.js

> Un pequeño servidor de Node.js que inicia la sesión de los usuarios con Facebook a través de OpenAuth.

Este servidor tiene dos direcciones: `/login/facebook/` empieza el inicio de sesión, y `/auth/` recibe al usuario de vuelta y lee el perfil. Solo usa Node.js (18 o posterior, por `fetch`).

## El código

Guárdalo como `app.js` y rellena las tres constantes del principio:

```js
const http = require('http');
const crypto = require('crypto');

const OPENAUTH = 'https://auth.example.com';   // your OpenAuth address
const TOKEN = 'paste-your-app-token-here';      // a token from Tokens in OpenAuth
const APP = 'https://www.example.com';          // the public address of this app

const server = http.createServer(async function(req, res) {

	const url = new URL(req.url, APP);

	// 1. The user clicks "Sign in with Facebook"
	if (url.pathname === '/login/facebook/') {

		const sessionid = crypto.randomUUID();

		const response = await fetch(OPENAUTH + '/', {
			method: 'POST',
			headers: { 'content-type': 'application/json', 'x-token': TOKEN },
			body: JSON.stringify({ serviceid: 'facebook', sessionid: sessionid, url: APP + '/auth/' })
		});

		if (!response.ok) {
			res.writeHead(502, { 'content-type': 'text/plain' });
			res.end('Sign-in is not available right now.');
			return;
		}

		const address = await response.json();
		res.writeHead(302, { location: address, 'set-cookie': 'signin=' + sessionid + '; Path=/; HttpOnly; SameSite=Lax' });
		res.end();
		return;
	}

	// 2. OpenAuth sends the user back here with ?sessionid=...
	if (url.pathname === '/auth/') {

		const sessionid = url.searchParams.get('sessionid');
		const cookie = (req.headers.cookie || '').match(/(?:^|;\s*)signin=([^;]+)/);

		if (!sessionid || !cookie || cookie[1] !== sessionid) {
			res.writeHead(400, { 'content-type': 'text/plain' });
			res.end('Invalid sign-in.');
			return;
		}

		const response = await fetch(OPENAUTH + '/sessions/?id=' + encodeURIComponent(sessionid), {
			headers: { 'x-token': TOKEN }
		});

		if (!response.ok) {
			res.writeHead(401, { 'content-type': 'text/plain' });
			res.end('The sign-in has expired. Please try again.');
			return;
		}

		const profile = await response.json();

		// 3. Find or create the user in your database by profile.serviceid + profile.id
		res.writeHead(200, { 'content-type': 'text/plain' });
		res.end('Hello ' + profile.name + ' (' + profile.email + ')');
		return;
	}

	res.writeHead(404, { 'content-type': 'text/plain' });
	res.end('Not found');
});

server.listen(3000);
```

## Ejecútalo

```bash
node app.js
```

Pon un enlace a `/login/facebook/` en tu página de inicio de sesión. Después de iniciar sesión, el usuario llega a `/auth/` y ve un saludo.

## Cómo funciona

- El ID de sesión es aleatorio y también se guarda en una cookie. En `/auth/`, el servidor solo acepta el ID de sesión que empezó este navegador, así nadie puede terminar un inicio de sesión con un enlace que le haya pasado otra persona.
- El token se queda en el servidor; el navegador nunca lo ve.
- Si el usuario tarda más de 15 minutos, `/sessions/` responde `404` y el servidor le pide que lo intente de nuevo.

En una app real, sustituye el saludo por tu propia sesión: busca al usuario por `profile.serviceid` y `profile.id` y luego inicia su sesión. Consulta [El perfil del usuario](../../reference/user-profile/).
