NextAuth.js Setup Sinhala | Next.js Authentication Tutorial
කොහොමද යාලුවනේ!
අද අපි කතා කරන්න යන්නේ Next.js applications වලට අතිශයින්ම වැදගත් දෙයක් ගැන. ඒ තමයි Authentication. ගොඩක් වෙලාවට අපි website එකක් හරි web application එකක් හරි හදනකොට users ලට login වෙන්න, profile maintain කරන්න පුළුවන් වෙන්න ඕනේ නේද? ඒකට තමයි Authentication කියන concept එක අපිට ඕන වෙන්නේ.
Authentication කියන්නේ user කෙනෙක් ඇත්තටම එයා කියන කෙනාමද කියලා confirm කරන process එක. මේක ටිකක් සංකීර්ණ දෙයක් වෙන්න පුළුවන්, මොකද usernames, passwords, sessions, cookies වගේ ගොඩක් දේවල් මේකට සම්බන්ධ වෙනවා. හැබැයි, Next.js භාවිතා කරන ඔබට මේ වැඩේ ගොඩක් ලේසි කරන නියම library එකක් තියෙනවා: ඒ තමයි NextAuth.js.
NextAuth.js කියන්නේ Next.js apps වලට authentication එකතු කරන්න තියෙන open-source library එකක්. මේක අපිට Google, GitHub, Facebook වගේ OAuth providers හරහා login පහසුකම් සලසා ගන්නත්, Email/Password login හදාගන්නත්, database එකක් එක්ක user management කරන්නත් උදව් වෙනවා. ඒ වගේම, session management, JWT (JSON Web Tokens) වගේ advanced දේවලුත් මේකෙන් බලාගන්න පුළුවන්.
අද මේ tutorial එකෙන් අපි බලමු NextAuth.js කියන්නේ මොකක්ද, ඒක Next.js project එකකට install කරගෙන, basic providers (විශේෂයෙන් Google සහ GitHub) හරහා login flow එකක් හදාගන්නේ කොහොමද, ඒ වගේම session management කරන්නේ කොහොමද කියලා. අවසානයේදී අපි පුංචි practical example එකක් හදලා මේක වැඩ කරන විදිය බලමු.
ඔබ Next.js developer කෙනෙක් නම්, මේක ඔබේ projects වලට අනිවාර්යයෙන්ම අවශ්ය වෙන skill එකක්. එහෙනම්, අපි පටන් ගමුද?
1. NextAuth.js කියන්නේ මොකක්ද?
NextAuth.js කියන්නේ Next.js frameworks එකට ගැලපෙන විදියට හදපු authentication library එකක්. මේක Next.js apps වලට authentication එකතු කරන ක්රියාවලිය සරල කරනවා. විශේෂයෙන්ම, SSR (Server-Side Rendering) සහ API Routes වගේ Next.js features එක්ක මේක ඉතාම හොඳින් වැඩ කරනවා.
NextAuth.js භාවිතා කිරීමේ වාසි:
- පහසු Setup එකක් (Easy Setup): ඉතාම සරලව Next.js project එකකට install කරලා configure කරන්න පුළුවන්.
- විවිධ Providers සඳහා සහයෝගය (Support for Various Providers): Google, GitHub, Facebook, Twitter වගේ ගොඩක් OAuth providers සඳහා built-in support එකක් තියෙනවා. ඒ වගේම Email/Password login, Database login වගේ options ත් තියෙනවා.
- Session Management: User sessions manage කරන එක NextAuth.js එකෙන් automatically කරනවා. මේක server-side සහ client-side දෙකේදීම පහසුවෙන් access කරන්න පුළුවන්.
- Security Features: CSRF protection, JWT encryption වගේ security features මේකේ built-in තියෙනවා.
- Callbacks සහ Adapters: Authentication flow එක custom කරන්න callbacks සහ databases එක්ක වැඩ කරන්න adapters provide කරනවා.
සරලවම කිව්වොත්, NextAuth.js නිසා අපිට authentication ගැන ගොඩක් වෙලාවක් වැය කරන්නේ නැතිව, අපේ core application features වලට අවධානය යොමු කරන්න පුළුවන්.
2. Setup එක පටන් ගමු!
දැන් අපි බලමු NextAuth.js library එක අපේ Next.js project එකට install කරගෙන, basic setup එක හදාගන්නේ කොහොමද කියලා.
2.1. NextAuth.js Install කිරීම
මුලින්ම, ඔබේ Next.js project එකේ terminal එක open කරලා පහත command එක run කරන්න:
npm install next-auth
# නැත්නම්
yarn add next-authමේකෙන් NextAuth.js library එක ඔබේ project එකට add වෙනවා.
2.2. API Route එක හදමු
NextAuth.js වැඩ කරන්නේ Next.js API Routes හරහා. ඒ නිසා අපි අලුත් API route එකක් හදන්න ඕනේ. මේක Next.js වල convention එකක් විදියට pages/api/auth/[...nextauth].js කියන path එකේ තියෙන්න ඕනේ.
ඔබේ project එකේ pages folder එක ඇතුළේ api කියලා folder එකක් හදලා, ඒ ඇතුළේ auth කියලා තවත් folder එකක් හදන්න. ඊට පස්සේ ඒ auth folder එක ඇතුළේ [...nextauth].js කියලා file එකක් හදන්න. (...nextauth කියන්නේ catch-all route එකක්.)
pages/api/auth/[...nextauth].js file එක ඇතුළට පහත code එක එකතු කරන්න:
import NextAuth from "next-auth";
export default NextAuth({
// Configure one or more authentication providers
providers: [
// Providers will go here later
],
// Optional: Add callbacks or database configuration here if needed
// callbacks: {},
// database: process.env.DATABASE_URL,
});මේක තමයි NextAuth.js configure කරන ප්රධානම file එක. මේ providers array එක ඇතුළට තමයි අපි පාවිච්චි කරන Google, GitHub වගේ authentication providers එකතු කරන්නේ.
2.3. Environment Variables සකස් කිරීම
Security එකට සහ configuration එක manage කරන්න, අපි sensitive data (API keys, secrets) .env.local file එකක store කරනවා. මේකෙන් production වලදී වුණත් secrets leak වීම වළක්වා ගන්න පුළුවන්.
ඔබේ project එකේ root directory එකේ .env.local කියලා file එකක් හදන්න. (මේක Git වලට commit වෙන්න දෙන්න එපා, ඒ නිසා .gitignore file එකේ .env.local කියලා තියෙනවද බලන්න.)
මේ file එකට පහත variables එකතු කරන්න:
NEXTAUTH_SECRET=ඔබේ_රහස්_කේතය_මෙතනින්
NEXTAUTH_URL=http://localhost:3000NEXTAUTH_URL: ඔබේ application එක run වෙන URL එක. Development වලදීhttp://localhost:3000වගේ වෙන්න පුළුවන්. Production වලදී ඔබේ domain name එක වෙන්න ඕනේ (උදා:https://yourdomain.com).
NEXTAUTH_SECRET: මේක අතිශයින්ම වැදගත්! NextAuth.js එකෙන් sessions encrypt කරන්න සහ JWT tokens sign කරන්න මේ secret එක භාවිතා කරනවා. මේක ඉතාම Strong, Random string එකක් වෙන්න ඕනේ. Production වලදී මේක කවුරුවත් අනුමාන කරන්න බැරි එකක් වෙන්න ඕනේ. ඔබට මේ වගේ එකක් generate කරගන්න පුලුවන්:
openssl rand -base64 32මේ command එක run කරාම එන string එක NEXTAUTH_SECRET එකට දාන්න.
දැන් අපි NextAuth.js install කරලා, API route එක හදලා, environment variables ටිකත් සකස් කරගත්තා. ඊළඟට බලමු මේකට providers එකතු කරන්නේ කොහොමද කියලා.
3. Basic Providers එකතු කරමු
NextAuth.js එකේ ප්රධාන වාසියක් තමයි විවිධ OAuth providers සඳහා support එකක් තිබීම. අපි දැන් Google සහ GitHub providers දෙකක් configure කරගමු.
3.1. Google Provider (Google හරහා Login වෙමු)
Google login enable කරන්න නම් අපිට Google Cloud Console එකෙන් OAuth credentials හදාගන්න ඕනේ.
- Google Cloud Console එකට යන්න: https://console.cloud.google.com/
- Project එකක් හදන්න: අලුත් project එකක් හරි තියෙන project එකක් හරි select කරන්න.
- Credentials හදන්න: Navigation Menu එකේ APIs & Services > Credentials යන්න. ඊට පස්සේ Create Credentials > OAuth client ID click කරන්න.
- OAuth Consent Screen එක configure කරන්න: මුලින්ම මේක කරන්න වෙනවා. User Type එක External විදියට තෝරලා, application name, support email, developer contact information වගේ දේවල් fill කරන්න.
- Application Type: Web application විදියට තෝරන්න.
- Authorized JavaScript origins:
http://localhost:3000(development සඳහා) - Authorized redirect URIs:
http://localhost:3000/api/auth/callback/google(development සඳහා)ප්රවේසමෙන්: Production වලදීhttp://localhost:3000වෙනුවට ඔබේ domain එක භාවිතා කරන්න.
මේ step ටික follow කරාම ඔබට Client ID එකක් සහ Client Secret එකක් ලැබෙයි. මේවා ඔබේ .env.local file එකට එකතු කරන්න:
GOOGLE_CLIENT_ID=ඔබේ_Google_Client_ID
GOOGLE_CLIENT_SECRET=ඔබේ_Google_Client_Secretදැන් pages/api/auth/[...nextauth].js file එක update කරමු, Google Provider එක add කරන්න:
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google"; // Google Provider එක import කරමු
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
// Add more providers here later
],
secret: process.env.NEXTAUTH_SECRET, // NEXTAUTH_SECRET එක මෙතනත් දෙන්න
});දැන් Google login එක configure කරලා ඉවරයි!
3.2. GitHub Provider (GitHub හරහා Login වෙමු)
Google වගේම GitHub login එකත් හදාගන්න පුළුවන්. ඒකටත් අපිට GitHub එකෙන් OAuth credentials ඕනේ.
- GitHub Developer Settings වලට යන්න: ඔබේ GitHub profile picture එක click කරලා Settings > Developer settings > OAuth Apps වලට යන්න.
- New OAuth App එකක් register කරන්න: New OAuth App button එක click කරන්න.
- Application Details fill කරන්න:
- Application name: ඔබේ app එකේ නම (උදා: NextAuth Demo)
- Homepage URL:
http://localhost:3000 - Authorization callback URL:
http://localhost:3000/api/auth/callback/github
Register කරාම ඔබට Client ID එකක් සහ Client Secret එකක් ලැබෙයි. (Client Secret එක Generate කරගන්න Generate a new client secret click කරන්න.) මේවාත් .env.local file එකට එකතු කරන්න:
GITHUB_CLIENT_ID=ඔබේ_GitHub_Client_ID
GITHUB_CLIENT_SECRET=ඔබේ_GitHub_Client_Secretදැන් pages/api/auth/[...nextauth].js file එකට GitHub Provider එකත් add කරමු:
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import GitHubProvider from "next-auth/providers/github"; // GitHub Provider එක import කරමු
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
GitHubProvider({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
],
secret: process.env.NEXTAUTH_SECRET,
});දැන් අපේ NextAuth.js backend එක Google සහ GitHub providers දෙකම එක්ක වැඩ කරන්න සූදානම්!
4. Session Management සහ භාවිතය
API routes configure කරාට පස්සේ, අපිට මේ session එක frontend එකේදී use කරන්න පුළුවන් වෙන්න ඕනේ. NextAuth.js මේකට SessionProvider සහ useSession hook එක provide කරනවා.
4.1. Session Provider එක
මුලින්ම, අපේ whole Next.js application එක SessionProvider එකෙන් wrap කරන්න ඕනේ. මේකෙන් තමයි NextAuth.js එකට client-side sessions manage කරන්න පුළුවන් වෙන්නේ. මේක pages/_app.js file එකේ කරන්න ඕනේ.
ඔබේ pages/_app.js file එක මේ වගේ update කරන්න:
import '../styles/globals.css';
import { SessionProvider } from 'next-auth/react'; // SessionProvider එක import කරමු
function MyApp({ Component, pageProps: { session, ...pageProps } }) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
);
}
export default MyApp;මෙහිදී pageProps: { session, ...pageProps } විදියට session prop එක _app.js ට ලබා දෙනවා. NextAuth.js එකෙන් automatically මේ session prop එක getServerSideProps හෝ getInitialProps වලින් inject කරනවා.
4.2. Frontend එකෙන් Session එක පාවිච්චි කරමු
දැන් අපේ application එක පුරාම useSession hook එක භාවිතා කරලා user session information access කරන්න පුළුවන්. ඒ වගේම signIn සහ signOut functions භාවිතා කරලා login/logout flow එක manage කරන්නත් පුළුවන්.
අපි දැන් pages/index.js file එකේ පුංචි login/logout page එකක් හදමු.
import { useSession, signIn, signOut } from 'next-auth/react';
export default function Home() {
const { data: session } = useSession(); // useSession hook එක භාවිතා කරලා session data ලබා ගන්නවා
if (session) {
// User කෙනෙක් login වෙලා නම්
return (
<div style={{ fontFamily: 'Arial, sans-serif', textAlign: 'center', marginTop: '50px' }}>
<h1>ආයුබෝවන්, {session.user.name || session.user.email}!</h1>
{session.user.image && (
<img
src={session.user.image}
alt="User profile"
style={{
borderRadius: '50%',
width: '100px',
height: '100px',
objectFit: 'cover',
marginBottom: '20px'
}}
/>
)}
<p>ඔබගේ Email එක: {session.user.email}</p>
<button
onClick={() => signOut()}
style={{
padding: '10px 20px',
fontSize: '16px',
backgroundColor: '#dc3545',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}}
>
Logout
</button>
</div>
);
}
// User කෙනෙක් login වෙලා නැත්නම්
return (
<div style={{ fontFamily: 'Arial, sans-serif', textAlign: 'center', marginTop: '50px' }}>
<h1>ඔබව සාදරයෙන් පිලිගනිමු!</h1>
<p>Login වී ඉදිරියට යන්න.</p>
<button
onClick={() => signIn('google')}
style={{
padding: '10px 20px',
fontSize: '16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer',
marginRight: '10px'
}}
>
Google සමඟ Login වන්න
</button>
<button
onClick={() => signIn('github')}
style={{
padding: '10px 20px',
fontSize: '16px',
backgroundColor: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}}
>
GitHub සමඟ Login වන්න
</button>
</div>
);
}
මේ code එකෙන් වෙන්නේ:
useSession()hook එකෙන් current user session එක retrieve කරනවා.sessionobject එකක් තියෙනවා නම් (user කෙනෙක් login වෙලා නම්), අපි user ගේ නම, email එක සහ profile picture එක display කරනවා, ඒ වගේම Logout button එකක් දෙනවා.sessionobject එකක් නැත්නම් (user කෙනෙක් login වෙලා නැත්නම්), අපි Google සහ GitHub හරහා login වෙන්න buttons දෙකක් දෙනවා.signIn('google')සහsignIn('github')කියන functions වලින් අදාළ provider හරහා authentication flow එක initiate කරනවා.
දැන් ඔබේ Next.js application එක run කරලා (npm run dev) බලන්න. ඔබට login/logout flow එක test කරන්න පුළුවන් වෙයි.
5. Common Issues සහ Best Practices
NextAuth.js භාවිතා කරනකොට මතක තියාගන්න ඕන වැදගත් කරුණු කිහිපයක් සහ පොදු ගැටළු ටිකක් ගැන කතා කරමු.
5.1. NEXTAUTH_SECRET එකේ වැදගත්කම
අපි කලින් කතා කරපු විදියට NEXTAUTH_SECRET එක ඔබේ application එකේ security එකට ඉතාම වැදගත්. මේක දුර්වල එකක් වුණොත් attacker කෙනෙකුට ඔබේ sessions hijack කරන්න පුළුවන්. ඒ නිසා:
- සෑම විටම strong, random string එකක් භාවිතා කරන්න (අවම වශයෙන් 32 characters).
- Production environment වලදී මේක securely store කරන්න (උදා: Environment variable management service එකක් හරහා).
- මේක Git repository එකට commit කරන්න එපා.
5.2. Callback URLs
OAuth providers (Google, GitHub) configure කරනකොට Authorized redirect URIs / Callback URLs නිවැරදිව දෙන්න ඕනේ. Development වලදී http://localhost:3000/api/auth/callback/[provider] වගේ දෙන්න පුළුවන්. හැබැයි Production වලදී ඔබේ live domain එක භාවිතා කරන්න ඕනේ:
උදා: https://yourdomain.com/api/auth/callback/google
මේවා වැරදි වුණොත් "Redirect URI mismatch" වගේ errors එන්න පුළුවන්.
5.3. Error Handling සහ Debugging
Authentication flow එකේදී errors එනවා නම්:
- Console logs බලන්න: Browser console එකේ සහ server-side console එකේ (Next.js dev server එක run වෙන terminal එකේ) errors check කරන්න.
- Network requests බලන්න: Browser DevTools (Network tab) එකෙන් OAuth flow එකේදී වෙන requests මොනවද, errors මොනවද කියලා බලන්න.
- Environment variables දෙවරක් check කරන්න:
.env.localfile එකේ Client ID, Client Secret, NEXTAUTH_SECRET, NEXTAUTH_URL නිවැරදිව තියෙනවද කියලා බලන්න. - Provider configuration check කරන්න:
pages/api/auth/[...nextauth].jsfile එකේ provider config එක නිවැරදිද කියලා බලන්න.
5.4. Refresh Tokens
මේ tutorial එකේදී අපි Refresh Tokens ගැන ගැඹුරින් කතා නොකලත්, මේක වැදගත් concept එකක්. OAuth flow එකේදී Access Token එකක් සහ සමහර වෙලාවට Refresh Token එකක් ලැබෙනවා. Access Token එකක් expire වුණාම, user ව ආයෙත් login කරන්න කියන්නේ නැතුව, Refresh Token එක භාවිතා කරලා අලුත් Access Token එකක් ලබාගන්න පුළුවන්. NextAuth.js එකෙන් මේවා automatically manage කරනවා, නැත්නම් ඔබට callbacks හරහා custom logic එකක් add කරන්න පුළුවන්.
අවසන් වශයෙන්
ඉතින් යාලුවනේ, මේ tutorial එකෙන් අපි NextAuth.js කියන්නේ මොකක්ද, ඒක Next.js project එකකට install කරගෙන, Google සහ GitHub වගේ basic providers හරහා authentication flow එකක් හදාගන්නේ කොහොමද, ඒ වගේම sessions manage කරන්නේ කොහොමද කියලා විස්තරාත්මකව ඉගෙන ගත්තා.
NextAuth.js කියන්නේ Next.js applications වලට authentication එකතු කරන්න තියෙන ඉතාම බලවත් සහ පහසු library එකක්. මේකෙන් ඔයාලට ඔබේ users ලට secure සහ smooth login experience එකක් දෙන්න පුළුවන්.
ඔබේ ඊළඟ Next.js project එකේදී අනිවාර්යයෙන්ම NextAuth.js භාවිතා කරලා බලන්න. මේකෙන් ඔබේ development time එක ගොඩක් ඉතුරු වෙයි.
මේ tutorial එක ගැන ඔබේ අදහස්, ප්රශ්න, හෝ ඔබේ අත්දැකීම් පහතින් Comment කරන්න. ඒ වගේම මේක තවත් කෙනෙකුට ප්රයෝජනවත් වෙයි කියලා හිතනවා නම් share කරන්න. ඔබට ජය!
සුභ දවසක්!