Next.js là một trong những frontend framework phổ biến nhất với React làm lõi. Nó có thể tạo HTML tĩnh hoặc render động trên client và server. Điều này làm cho nó trở thành công cụ đa dụng cho mọi loại ứng dụng và website. Và điều tốt nhất: nó open-source, dùng miễn phí!
NextAuth là thư viện thứ 3 cho Next.js giúp tích hợp các identity provider và database khác nhau. Bạn tiết kiệm thời gian đăng ký cho user và vẫn có tất cả thông tin tài khoản quan trọng trong database bạn chọn. NextAuth hỗ trợ hơn 50 authentication provider bao gồm GitHub, Google, Facebook, Coinbase và nhiều hơn nữa.
NextAuth Upstash Redis Adapter
Hiện tại, Upstash Redis là một trong các database được NextAuth hỗ trợ!
Adapter upstash-redis NextAuth sử dụng Upstash HTTP client, hoạt động trên nhiều dịch vụ hosting. Bạn có thể dùng một free tier Redis database cho nhiều ứng dụng NextAuth với prefix.
Hãy tìm hiểu NextAuth với adapter mới phát hành này.
Ví dụ NextAuth với Upstash Redis
Cần Node.js phiên bản ít nhất 16.13.2. Cần tài khoản GitHub và Upstash.
Thiết lập ứng dụng
Tạo Next.js app cơ bản; template learn-starter ổn cho ví dụ này.
Dùng lệnh sau:
$ npx create-next-app nextauth-upstash-redis \
--use-npm \
--example "https://github.com/vercel/next-learn/tree/master/basics/learn-starter"
Dùng package dotenv để setup credentials dễ dàng hơn. Cài dotenv, NextAuth, Redis adapter, Upstash HTTP Redis client:
$ npm i dotenv next-auth @upstash/redis @next-auth/upstash-redis-adapter
Tạo API endpoint xác thực
API endpoint NextAuth là file JS đơn giản, tạo tại pages/api/auth/[...nextauth].js với nội dung:
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";
import { UpstashRedisAdapter } from "@next-auth/upstash-redis-adapter";
import { Redis } from "@upstash/redis";
import "dotenv/config";
export default NextAuth({
adapter: UpstashRedisAdapter(
new Redis({
url: process.env.UPSTASH_REDIS_URL,
token: process.env.UPSTASH_REDIS_TOKEN,
})
),
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
});
UpstashRedisAdapter wrap upstashRedisClient, bạn cung cấp credentials Upstash từ biến môi trường. Trong ví dụ này, chúng sẽ được load qua dotenv từ file .env trong thư mục root. Tương tự cho GitHub provider.
Thiết lập biến môi trường
Tạo file .env với nội dung:
UPSTASH_REDIS_URL=
UPSTASH_REDIS_TOKEN=
GITHUB_ID=
GITHUB_SECRET=
Lấy credentials Upstash từ Upstash console. Đăng nhập, tạo database và click vào nó trong overview. Hình 1 hiển thị vị trí chứa credentials cần thiết.
Lấy credentials GitHub provider khi đăng ký OAuth Application mới cho tài khoản GitHub. Hình 2 hiển thị form đăng ký. Để chạy local, dùng https://localhost:3000 làm URLs.

Sau khi đăng ký app, bạn nhận Client ID và tạo secret bằng nút "generate new client secret".
Sau khi setup services, bạn cũng muốn cung cấp session data NextAuth fetch cho app components.
Tạo file pages/_app.js với nội dung:
import { SessionProvider } from "next-auth/react";
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
);
}
Code này cung cấp session data cho tất cả component trong Next.js app để kiểm tra user đã đăng nhập hay chưa.
Để test, cập nhật trang index tại page/index.js với code:
import { useSession, signIn, signOut } from "next-auth/react";
export default function Home() {
const { data: session } = useSession();
if (session) {
const { email, image, name } = session.user;
return (
<>
<img src={image} width="150" />
<br />
Signed in as {name} ({email})
<br />
<button onClick={signOut}>Sign out</button>
</>
);
}
return <button onClick={signIn}>Sign in</button>;
}
Nếu session tồn tại, hiển thị ảnh profile, tên, email của user hiện tại. Nếu không, chỉ hiện nút sign-in tự động redirect đến trang login.
Test ứng dụng
Chạy lệnh sau để test:
$ npm run dev
Lệnh này khởi động HTTP server tại port 3000, mở trong trình duyệt. Nếu mọi thứ tốt, bạn sẽ thấy nút sign-in. Click và cho phép app kết nối GitHub.
Nếu signup thành công, bạn sẽ redirect về trang index và thấy thông tin GitHub account.
Sử dụng nhiều ứng dụng với một Redis Database
Upstash cung cấp một free Redis database cho mỗi tài khoản. Bạn có thể dùng database này cho nhiều ứng dụng riêng biệt, với prefix thêm vào tất cả keys ghi vào storage.
Để thiết lập, sửa code trong pages/api/auth/[...nextauth].js. Adapter factory function nhận đối số thứ 2 bên cạnh Upstash Redis client.
UpstashRedisAdapter(
new Redis({
url: process.env.UPSTASH_REDIS_URL,
token: process.env.UPSTASH_REDIS_TOKEN,
}),
{
baseKeyPrefix: "app-specific-prefix-1:"
}
);
Cách này đảm bảo user của nhiều app không va chạm trong database.
Kết luận
NextAuth là thư viện tiện lợi setup authentication cho ứng dụng không rắc rối. Cùng sự dễ dàng đó là Upstash Redis, dịch vụ hosting Redis database đơn giản. Với adapter NextAuth database mới cho Upstash Redis, hai cái này tạo ra sự kết hợp mạnh mẽ cho phép bạn tạo ứng dụng mới trong tích tắc!
Upstash Redis là serverless database; bạn chỉ trả tiền cho thứ bạn dùng, nên bạn có thể test và lặp lại nhiều MVP mà không lo hóa đơn khổng lồ cho app chưa có user.