I want to integrate with AppWrite with my NextJS app, but I'm having trouble understanding the flow. What is the best way to keep the session "active", write http-only cookie with the value of the SessionObject returned from AppWrite? Here is a current POC i'm working with:
context/auth.js
const client = new Client();
client.setEndpoint('SOME_SERVE').setProject('SOME_PROJ');
const account = new Account(client);
const AuthContext = createContext();
export function useAuth() {
return useContext(AuthContext);
}
export function AuthProvider(props) {
const [user, setUser] = useState(null);
function signIn(email, password) {
const promise = account.createEmailSession(email, password);
promise.then(
function (response) {
console.log(response);
setUser(response); // Success
},
function (error) {
console.log(error);
setUser(null); // Failure
}
);
}
return (
<AuthContext.Provider value={{ user, signIn, signOut, signUp }}>
{props.children}
</AuthContext.Provider>
);
}
pages/login/index.tsx
export default function Login() {
const { signIn } = useAuth();
const username = useRef();
const password = useRef();
async function handleSubmit(e) {
e.preventDefault();
try {
await signIn(username.current.value, password.current.value);
Router.push("/account")
} catch (err) {
console.log(err);
}
}
return (
<SomeLoginForm username password />
);
}
pages/account/index.tsx this represents a private page, only accessible by someone who has an active session
export default function Account() {
const { user } = useAuth();
useEffect(() => {
if (user === null) {
Router.push("/login");
}
}, [])
return (
<Greetings user />
);
}