You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
So recently, I added next auth to my code because I wanted to implement a new function, which is to allow my users to send emails through my app by signing in to their Google account.
I made a lot of progress in the code, but the latest issue I ran into is that when I go to api/auth/session, I can see my login info like e-mail, access_token etc.
But when I try to use Gmail API to send the email using information from said session, I get an error saying "You must be signed in".
Here is my code (api/auth/[...nextauth]/route.ts):
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
declare module "next-auth" {
interface Session {
user: {
email?: string;
};
accessToken?: string;
}
}
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
checks: ["none"],
authorization: {
params: {
scope:
"openid email profile https://www.googleapis.com/auth/gmail.send",
prompt: "consent",
},
},
}),
],
});
export { handler as GET, handler as POST };
api/sendEmail/route.ts:
import { NextResponse } from "next/server";
import { getSession } from "next-auth/react";
import { google } from "googleapis";
export async function POST(req) {
const session = await getSession({ req: { headers: req.headers } });
if (!session || !session.accessToken) {
return new Response(JSON.stringify({ error: "You must be signed in." }), {
status: 401,
});
}
const { accessToken } = session;
if (!session) {
return NextResponse.json({ error: "You must be signed in." });
}
const { to, subject, body } = await req.json();
try {
// Send the email using the Gmail API
const gmail = google.gmail({ version: "v1", auth: accessToken });
const encodedEmail = // ... encode the email in the required format
await gmail.users.messages.send({
userId: "me",
requestBody: {
raw: encodedEmail,
},
});
return NextResponse.json({ message: "Email sent successfully" });
} catch (error) {
return NextResponse.json({ error: "Error sending email" });
}
}
components/send-email.tsx:
// SendEmailForm.tsx
import React, { useState } from "react";
import { useSession, signIn } from "next-auth/react";
interface EmailFormData {
to: string;
subject: string;
message: string;
}
const SendEmailForm: React.FC = () => {
const { data: session, status } = useSession();
console.log("Client-side session:", session);
const [formData, setFormData] = useState<EmailFormData>({
to: "",
subject: "",
message: "",
});
const handleChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e: React.FormEvent) => {
console.log(formData);
e.preventDefault();
try {
const response = await fetch("/api/sendEmail", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify(formData),
});
console.log(response);
if (!response.ok) {
const errorBody = await response.text(); // or response.json() if the server sends JSON
console.error("Error response body:", errorBody);
throw new Error(`Error: ${response.statusText}`);
}
const result = await response.json();
console.log("Email sent successfully:", result);
// Reset form or show success message
} catch (error) {
console.error("Failed to send email:", error);
// Show error message
}
};
if (status === "loading") {
return <p>Loading...</p>;
}
if (!session) {
return (
<div>
<p>You must be logged in to send emails.</p>
<button onClick={() => signIn()}>Log in</button>
</div>
);
}
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="to">Recipient Email:</label>
<input
type="email"
id="to"
name="to"
value={formData.to}
onChange={handleChange}
required
/>
</div>
<div>
<label htmlFor="subject">Subject:</label>
<input
type="text"
id="subject"
name="subject"
value={formData.subject}
onChange={handleChange}
required
/>
</div>
<div>
<label htmlFor="message">Message:</label>
<textarea
id="message"
name="message"
value={formData.message}
onChange={handleChange}
required
/>
</div>
<button type="submit">Send Email</button>
</form>
);
};
export default SendEmailForm;
And then finally page where my component is displayed (email/page.tsx):
The only thing I'm not understanding is why when I open api/auth/session I can see all of my information, and even on the frontend when I apply the principal of: if there is a session show email form, otherwise say "you must login" the email form does show meaning my code recognizes I'm logged in.
But once the information gets sent to sendEmail api, it says I'm unauthorized, aka I must sign in.
If anyone had a similar issue before, or sees an error in my code with how props or session is being passed, please let me know since I am pretty new to using next auth.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
So recently, I added next auth to my code because I wanted to implement a new function, which is to allow my users to send emails through my app by signing in to their Google account.
I made a lot of progress in the code, but the latest issue I ran into is that when I go to api/auth/session, I can see my login info like e-mail, access_token etc.
But when I try to use Gmail API to send the email using information from said session, I get an error saying "You must be signed in".
Here is my code (api/auth/[...nextauth]/route.ts):
api/sendEmail/route.ts:
components/send-email.tsx:
And then finally page where my component is displayed (email/page.tsx):
The only thing I'm not understanding is why when I open api/auth/session I can see all of my information, and even on the frontend when I apply the principal of: if there is a session show email form, otherwise say "you must login" the email form does show meaning my code recognizes I'm logged in.
But once the information gets sent to sendEmail api, it says I'm unauthorized, aka I must sign in.
If anyone had a similar issue before, or sees an error in my code with how props or session is being passed, please let me know since I am pretty new to using next auth.
Many thanks in advance :)
Beta Was this translation helpful? Give feedback.
All reactions