implementing routing with or without login #895
-
Hi. I'm implementing page access restrictions based on login or not. The logged-in user information (e.g. However, there is a problem when moving from If I'm using the routing system incorrectly, I'd like you to teach me how to use the routing system correctly. // _default.page.route.tsx
import type { PageContext } from './types';
export const CONDITIONAL_ACCESSIBLE_PAGE = ['/login', '/signup'];
export async function onBeforeRoute(pageContext: PageContext) {
const { token } = pageContext;
/**
* @token
* @user { isLoggedIn: boolean; info: UserInfo } (default: { isLoggedIn: false; info: null })
*/
try {
let fetch;
if (typeof window === 'undefined') {
const nodeFetch = await import('node-fetch');
fetch = nodeFetch.default;
const res = await fetch(`http://localhost:5000/api/users/check-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token: token }),
});
const authInfo: any = await res.json();
return {
pageContext: {
user: {
isLoggedIn: authInfo.auth || false,
info: authInfo.auth ? authInfo.user : null,
},
},
};
} else {
fetch = window.fetch;
const res = await fetch(`http://localhost:5000/api/users/`);
const authInfo: any = await res.json();
return {
pageContext: {
user: {
isLoggedIn: authInfo.success || false,
info: authInfo.success ? authInfo.user : null,
},
},
};
}
} catch (err) {
console.error(err);
}
} // /pages/login/index.page.route.ts
// /pages/signup/index.page.route.ts
import { CONDITIONAL_ACCESSIBLE_PAGE } from '../../renderer/_default.page.route';
import type { PageContext } from '../../renderer/types';
export default (pageContext: PageContext) => {
if (userIsLoggedIn(pageContext)) {
if (pageContext.urlOriginal && CONDITIONAL_ACCESSIBLE_PAGE.includes(pageContext.urlOriginal)) {
return false;
}
}
return true;
};
function userIsLoggedIn(pageContext: PageContext) {
return pageContext.user.isLoggedIn;
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Why don't you resolve the user before calling |
Beta Was this translation helpful? Give feedback.
Why don't you resolve the user before calling
renderPage()
? I don't see the need to do it also on the client-side?