iTranslated by AI
[Next.js + GAS] Building and Operating a Dynamic Lab Website Using Google Sheets
I have summarized the specifications and implementation methods, along with the actual source code, regarding the website I created and released for my laboratory, which previously lacked a web presence. I hope this serves as a platform for reporting our activities.
This article will be long because it covers the entire process from design-conscious implementation to release and initial operation.
Conclusion
First, I will present the site and repository that are the results of this article.
Homepage
GitHub
Purpose
Goals to achieve
- Dynamically update laboratory members, journal publications, news, etc.
- Improve maintainability by managing data in a tabular format like a spreadsheet.
- Enhance usability.
To build a site focusing on these three points, I used Next.js and Google Apps Script as mentioned in the title.
Technologies Used
- Next.js
- Google Apps Script
- TypeScript・SCSS
CSS (SCSS) was written from scratch. For icons, I used Font Awesome Free Icons. I believe it is important to maintain a sense of unity, such as consistently using Bootstrap Icons if that is your choice.
- Vercel
It is more of a service than a technology, but this is the platform used for deployment.
Selection Reasons
- Next.js is highly recognized as a web framework and excels at both server-side rendering and static site generation.
- It is a framework with extensive documentation, which is helpful when other contributors add features or fix bugs after I have built it.
- Cache timing is easy to adjust.
- GAS is a Google service that integrates with Spreadsheets, so the learning cost is low, and it allows for management while viewing the whole dataset as a table.
Design
In the initial design stage, the "dreaming phase," we use whiteboards or similar tools to think about what would be nice to achieve. We consider which pages are necessary and what information should be displayed. The operational method is particularly important, and it is crucial to minimize the cost of updating articles as much as possible.
Development (TypeScript)
I have received permission from the faculty member of this laboratory to post the following images and text.
The development steps until issuing v1.0.0 were as follows:
- Verification of GAS operation using TypeScript
- Display of the project list
- Design of the project detail page
- Design of the news section
- Creation of other pages
- Design of client component parts
├─public
└─src
├─app
│ ├─award
│ ├─contact
│ ├─member
│ ├─news
│ │ └─[slug]
│ ├─project
│ │ └─[slug]
│ ├─publication
│ ├─thesis
│ └─[...notfound]
├─components
│ └─... (Omitted)
└─styles
├─app
│ ├─award
│ ├─contact
│ └─... (Omitted)
├─components
└─global
GAS Setup
This time, I decided to retrieve four types of information separately:
- Members
- Projects
- News
- Awards
Since the operations are the same, I will explain using "News" as an example.
Creating JSON for News
I created the following header row in a spreadsheet and described the actual data starting from the second row.
| a | b | c | d | e | f | g |
|---|---|---|---|---|---|---|
| id | Date | Title | Content (HTML allowed) | Thumbnail URL | Related Links (Separator ";") | Additional Image URLs (Separator ";") |
The id can be set as a string freely, not just numerical values.
The main body (content) is entered as a string so that users can insert tags like <a> or <detail>.
The goal is to convert the content of the spreadsheet into JSON format. Access Extensions -> Apps Script from the ribbon. Once Code.gs is generated, I wrote the following code.
function readData() {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const target_sheet = spreadsheet.getSheetByName('News');
const last_row = target_sheet.getLastRow();
const range = target_sheet.getRange(`A2:G${last_row}`);
const data_values = range.getValues();
const json_data = data_values.map((data_row) => {
// Split by ";" and convert to a list
const formatToObjects = (str) => str.split(';').map(name => ({ name }));
let linksArray = formatToObjects(data_row[5]); // Column F
if (linksArray.length === 1 && linksArray[0].name === "")
linksArray = []
let imagesArray = formatToObjects(data_row[6]); // Column G
if (imagesArray.length === 1 && imagesArray[0].name === "")
imagesArray = []
return {
id: data_row[0], // Column A
date: data_row[1], // Column B
title: data_row[2], // Column C
article: data_row[3], // Column D
thumbnailURL: data_row[4], // Column E
links: linksArray,
additionalImageURL: imagesArray,
}
});
console.log(json_data)
return json_data;
}
function doGet() {
const data = readData();
const response = ContentService.createTextOutput();
response.setMimeType(ContentService.MimeType.JSON);
response.setContent(JSON.stringify(data));
return response;
}
The formatToObjects() function used for linksArray and imagesArray splits the string by ; and converts it into a list.
Then, if the array length is 1 and the string at index 0 is empty (i.e., an empty cell), it replaces the elements to have a count of zero.
You can verify the operation by clicking ▷ Run.
Once preparation is complete, deploy it as a web app from the Deploy menu.
Create similar scripts for items other than news as well.
Click here for the news generation result (Deployment result)
Next.js Setup
Set up the Next.js project using create-next-app. The package manager used is pnpm, and we will use the App Router.
Reading JSON Data from GAS
Now, we actually read the data.
// Every 5 minutes
export async function fetchNews() {
const response = await fetch(sai_news, {
next: { revalidate: 300 },
});
return response;
}
I assigned sai_news=(the previous URL) as the first argument to the fetch function and passed the following as the second argument:
{
next: { revalidate: 300 },
}
The intention behind the second argument will be explained in the next section.
(Supplement) Caching Countermeasures
In Next.js, once data is cached after deploying to Vercel, it is kept persistently.
Duration
The Data Cache is persistent across incoming requests and deployments unless you revalidate or opt-out.
(https://nextjs.org/docs/app/building-your-application/caching#duration-1)
Duration (Translation)
Data Cache is persistent across incoming requests and deployments unless you revalidate or opt-out.
News updates are included in the dynamic updates intended for this project. I believe that news should be reflected within about 10 minutes after posting.
- Opting out
As mentioned in the quote, opting out allows you to always get the latest state because it tries to fetch new data without keeping a cache. However, issues like GAS API response times and call limits arise, compromising the smoothness of page rendering.
- Revalidation
The quote also suggests another method. There are two patterns: time-based revalidation and on-demand revalidation. Specifically, time-based revalidation is a method close to our goal.

How Time-based Revalidation Works
(Source: https://nextjs.org/docs/app/building-your-application/caching)
The first fetch reads from the Data Source and stores it in the cache. Subsequent accesses display the data from the cache. Then, during an access when revalidation occurs, the cached content is shown while data is fetched in the background and stored in the cache. Therefore, it is possible to update data in a natural flow.
To enable this method, I passed a JSON object as the second argument in Reading JSON Data from GAS. In this case, since it says 300, it means 300s = 5 minutes, and the latest data will be reflected every 5 minutes.
Fetching the Project List
Now that data fetching is possible, I will proceed with the project page. The requirements for the project list are as follows:
- Search function by partial match (OR logic)
- Display categorized by fiscal year
- Grouping projects with high similarity
I will make it a client component so that the displayed results change dynamically.
First, since /project/ itself is a server component, it retrieves the project JSON and creates a list. To handle the possibility of empty data in the list, I set a filter condition with item.id !== "" to filter out empty items.
Then, I create a <ProjectViewer /> and design the rendering part.
Displaying the Project List
First, I will show the type definition for the project JSON data.
export interface Author {
name: string; // Author name
}
export interface Tag {
name: string; // Keyword
}
export interface AdditionalImage {
name: string; // URL of additional image to display
}
export interface Project {
id: string; // Identifier string that also serves as part of the URL
classification: string; // Journal, international conference, etc.
type: string; // With/without international peer review, etc.
title: string; // Research title, etc.
authors: Author[]; // List of author names
tags: Tag[]; // List of keywords
bookTitle: string; // Beginning of journal (proceedings) info
volume: string;
number: string;
pageStart: number;
pageEnd: number; // End of journal (proceedings) info
date: Date; // Publication date
abstract: string; // Summary description
url: string; // Related link (1 item)
citation: string; // Citation text
paperUrl: string; // Document URL
thumbnailURL: string; // Thumbnail image URL
presentationHTML: string; // HTML field for presentation
documentHTML: string; // HTML field for document
posterHTML: string; // HTML field for poster, etc.
freeHTML: string; // Other HTML field
additionalImageURL: AdditionalImage[]; // Array of additional images
}
Since this appears many times later in the article, I have added comments describing what each field contains.
This is the description of the part that renders the embedded display section using a list.
Grouping
Regarding grouping, items with the same thumbnail image URL are treated as a single group.

Grouped projects
function groupByThumbnail(array: Project[]) {
var grouped: { [name: string]: Project[] } = {};
// Group if the thumbnail paths match
array.forEach((item) => {
if (item.thumbnailURL !== "" || item.thumbnailURL) {
// Create key if it doesn't exist
if (!grouped[item.thumbnailURL]) {
grouped[item.thumbnailURL] = [];
}
grouped[item.thumbnailURL].push(item);
} else {
// Case for default thumbnail
if (!grouped[item.id]) {
grouped[item.id] = [];
}
grouped[item.id].push(item);
}
});
return grouped;
}
By creating it as a dictionary type like this, {string key: project array} can be realized.
(Supplement) Calculating the Display Fiscal Year
Since this is a school laboratory, I want to display items categorized by fiscal year.
First, the calculation for the fiscal year is as follows:
const fiscalYear: number = time.getMonth() + 1 > 3 ?
time.getFullYear() :
time.getFullYear() - 1;
Since months 1 to 12 are assigned values 0 to 11, the getMonth method returns 3 for April.
Therefore, filtering by a specific fiscal year looks like this:
const matchedDataWithYear = displayArray?.filter((item) => {
const japanTime = new Date(
new Date(item.date).toLocaleString("en-US", {
timeZone: "Asia/Tokyo",
})
);
// Calculate fiscal year
return (
(japanTime.getMonth() + 1 > 3
? japanTime.getFullYear()
: japanTime.getFullYear() - 1) === year
);
});
About japanTime
Dates converted to ISO format (ISO 8601) by the spreadsheet can be converted back to a Date type with new Date(), but at the spreadsheet level, they are set to GMT+0 and are not in Japan Standard Time.
const japanTime = new Date(
new Date(item.date).toLocaleString("en-US", {
timeZone: "Asia/Tokyo",
})
);
By forcibly changing the time zone with this code, we correct the discrepancy when viewing the site from Japan.
Searching in the Project List
Now that data fetching is possible, I will proceed with the project page. The requirements for the search system in the project list are as follows:
- Keyword search by splitting the input with spaces and displaying results using logical OR.
- Execute the search by pressing the Enter key after input.
- Ability to configure search conditions.
To ensure most users find it intuitive:
- Provide a dropdown list for selecting search conditions.
- Compose the interface of an input field, a dropdown, and a search/clear button.
I designed the list using an OS-dependent dropdown, and for the button that displays the current selection, I applied CSS with appearance: none;.
Using the Enter Key for Searching
I implemented a mechanism to execute the search when the Enter key is pressed while the input field is focused.
<input
title="Enter search conditions"
value={searchWord}
placeholder={
initialQ
? `Tap ${isUsingPhone ? "X" : "click"} to clear`
: `${isUsingPhone ? "Tap" : "click"} to enter` // Note: "tap" for mobile, "click" for desktop
}
type={"text"}
className={`${styles.search_input}`}
onInput={triggerSearchInput}
onKeyDown={handleEnterKeyPress}
/>
Within handleEnterKeyPress, the code determines if the Enter key was pressed and only proceeds with the search if the field is not empty.
Function to Execute the Search
The search logic branches based on the condition selected from the mode dropdown list, with filtering functions written for each.
Creating Search Keywords from the Input Field
const filterKeywords = _searchWord.split(/[ ]+/);
The regex inside [] includes both half-width and full-width spaces, converting all of them within the input field into a list of keywords.
if (filterKeywords.every((keyword) => keyword === "")) {
setUserFiltered(false);
router.push(`/project/`);
setDisplayingSearchCondition(null);
return;
}
Searching by Title
filteredArray = lists?.filter((project) =>
filterKeywords.some(
(keyword) =>
keyword.toLowerCase() !== "" &&
project.title.toLowerCase().includes(keyword.toLowerCase())
)
);
A double loop is created between the keywords and each project; if at least one combination returns true, the project is included in the filtered results. It checks the logical AND of two conditions: whether the keyword is not empty and whether the title (lowercase) contains the keyword (lowercase).
Searching by Author Name
filteredArray = lists?.filter((project) =>
filterKeywords.some((keyword) =>
project.authors.some(
(author) =>
keyword.toLowerCase() !== "" &&
(author.name
.toLowerCase()
.replace(/[ ]+/, "")
.includes(keyword.toLowerCase()) ||
author.name
.toLowerCase()
.split(/[ ]+/)
.reverse()
.join("")
.includes(keyword.toLowerCase()))
)
)
);
The search principle is the same as the "Title" search. The differences are:
- It uses a triple loop because
authorsis also an array. - Since the order of First name and Last name might be reversed, I also search against a version of the name string where the space-separated parts are reversed.
- I strip spaces from the
authorstring to ensure consistent matching.
I have omitted the sections for keywords and publication year since they are essentially versions of the author search without the stripping or numerical matching.
(Supplement) Initial Search upon Page Jump
To display search results immediately upon page load (useful for shared links or specific author searches), I used two URL parameters that are processed when the page loads.
const router = useRouter();
const params = useSearchParams();
const initialMode = params.get("mode");
const initialQ = params.get("q");
Example: /project?mode=name&q=sensing,glasses → "Searches research titles for 'sensing' OR 'glasses'."
About using useSearchParams
When using useSearchParams, it is recommended to wrap the component in <Suspense>. In fact, I encountered an error during next build without it.
Since the fallback property of <Suspense /> can be set, I configured it to display a loading animation while the project list is being fetched.
useEffect(() => {
// (Omitted)
if (projects) {
setLoaded(true);
if (initialQ) {
const initialSearchWord = initialQ.replace(/,/g, " ");
setSearchWord(initialSearchWord);
let mode: string | null = null;
if (initialMode === "mode") {
mode = "research_name";
} else if (initialMode === "author") {
mode = "research_author";
} else if (initialMode === "keyword") {
mode = "research_tag";
} else if (initialMode === "year") {
mode = "research_year";
}
searchProjects(initialSearchWord, mode, projects);
setUserFiltered(true);
}
}
}, []);
As shown in the example, since q is comma-separated, I replace commas with spaces to convert it into a single search string. I map the mode parameter accordingly and pass these as arguments to the searchProjects function. Arguments are passed explicitly here to ensure the search is executed only once by the function rather than on every re-render.
Project Detail Display
Now, I will build the detail page, which is the destination after clicking an item in the list.
I search for the project using the find method.
const project: Project | undefined = filteredProjects.find(
(c: { id: string }) => {
const cid = String(c.id);
return cid === slug;
}
);
As indicated by the file path [slug], I determine the project by checking if it matches the slug. (It is necessary to cast the id to a string; otherwise, comparison might fail if the id is a number.)
Converting string to HTML Elements
Basically, I write code centered around patterns like project.abstract ? trueContent : <></>.
However, variables ending in HTML (such as documentHTML or presentationHTML) may contain HTML tags.
For this, I used the html-react-parser package to convert these strings into HTML elements.
In the file where I imported it as follows:
import parse from "html-react-parser";
I implemented it like this to perform the actual conversion:
{project.posterHTML ? (
<>
<h2 id="poster" className={styles.section_name}>
Poster
</h2>
<div className={`${styles.slide_box} ${styles.poster}`}>
{parse(project.posterHTML)}
</div>
</>
) : (
<></>
)}
(Supplement) News Screen Design
For the news screen:
The algorithms and design patterns are exactly the same, so I will omit the details in this article.
Displaying Lists such as Thesis, Publications, and Awards
These three pages have very similar structures, so I will describe them together. I will use the publication (Research Achievements) page as a representative example.
Basically, server components are sufficient for these pages.
Filtering Items to List from Projects
const sortedConferencePapers = filteredProjects?.filter(
(element) =>
element.classification.toLowerCase().includes("国内会議") ||
element.classification.toLowerCase().includes("国際会議") ||
element.classification.toLowerCase().includes("論文誌")
);
I assume the items to be displayed contain one of these words, so I use the boolean return value of includes for filtering.
Creating a Year List
I want to split the display by fiscal year. The list created here will also be utilized in the Design of the Table of Contents section.
const uniqueYears = Array.from(
new Set(
sortedConferencePapers?.flatMap((item) => {
const japanTime = new Date(
new Date(item.date).toLocaleString("en-US", {
timeZone: "Asia/Tokyo",
})
);
return japanTime.getMonth() + 1 > 3
? japanTime.getFullYear()
: japanTime.getFullYear() - 1;
})
)
);
The method for determining the fiscal year is the same as in Calculating the Display Fiscal Year. Since the flatMap function creates a one-dimensional array, I append the result to the array if it matches.
From there, simply looping through the years and displaying items by category leads to the desired display.
(Supplement) Design of the Table of Contents
This is the year-based table of contents displayed on the Thesis, Publication, and Awards pages. (The specification for the left sidebar on the project detail page is similar.)
I display this by passing uniqueYears: number[], which was created in Creating a Year List, to the component.
Displaying Members
This section displays the laboratory members. The requirements are as follows:
- Display name and English name.
- Display links to personal homepages or GitHub if they exist.
- Indicate variant characters (itai-ji), etc., if any.
- Enable direct searching of each individual's projects.
Incidentally, the list is divided into three groups for display, based on the following conditions:
- Faculty: Whether "Faculty" is included in the affiliation (
belonging). - Enrolled: Those excluding groups 1 and 3.
- Graduated/Alumni: Whether "Graduated" or "Completed" is included in the affiliation (
belonging).
Therefore, if someone does not match any specific condition, they are categorized into group 2.
const sortedEnrolledMember = members?.filter((element) => {
return (
!sortedMemberWithGraduation?.some(
(sortedMember) => sortedMember.id === element.id
) &&
!sortedMemberWithTeacher?.some(
(sortedMember) => sortedMember.id === element.id
)
);
});
After dividing into three groups, I attempted to render efficiently using a function that returns HTML elements (the same approach was used for /publication/ and /thesis/).
(Supplement) Handling Variant Characters and Project Search
One issue occurred when searching from the member display: if variant characters (itai-ji) are used in the project author field, they might not appear in the search results.
Example: 髙田/高田 (where "髙" is a platform-dependent character).
To account for automatic link generation, I added a "Variant Characters, etc." column to the spreadsheet.
| Name | Variant Characters, etc. |
|---|---|
| 髙田 | (高田) |
By entering data as shown above, I included these variations in the search parameters.
- Q. Why use parentheses instead of commas?
- A. Because using parentheses makes it easier to distinguish alternative notations when looking through the list in the spreadsheet.
Extraction from Parentheses
To extract from strings like (Takada)(John), I joined the strings using the following method:
item.otherName
.match(/\([^()]+\)/g) // Extract text within parentheses
?.flatMap((match) => match.split(",")) // Split by commas (countermeasure)
.flatMap((match) => match.slice(1, -1)) // Remove parentheses
.map((match) => match.replace(/[ ]+/g, " ")) // Trim spaces
.join(",") // Join strings
Creating Search Links
<Link
href={`/project?mode=author&q=${
item.name.replace(/[ ]+/, "") // Name
},${item.englishName.replace(/[ ]+/, "") // English Name
},${item.englishName.split(/[ ]+/).reverse().join("")}${ // English Name (reversed order)
item.otherName // Variant characters, etc.
? `,${item.otherName // If true
.match(/\([^()]+\)/g)
?.flatMap((match) => match.split(","))
.flatMap((match) => match.slice(1, -1))
.map((match) => match.replace(/[ ]+/g, ""))
.join(",")}`
: "" // If false
}`}
className={styles.search_link}
title="Search projects"
>
{/* Omitted */}
</Link>
While expanding this string joining within href makes it slightly harder to read, it allows almost all relevant projects to be included in the search results with a single link.
Creating the Top Page
Finally, the top page. The requirements are as follows:
- Display the 5 most recent news items.
- Install a language switching button (JP <=> EN).
To handle cases where there are fewer than 5 news items:
const listingNum = newsList ? (newsList.length > 5 ? 5 : newsList.length) : 0;
Language Switching
Next.js provides i18n support, making it easy to create pages for each language. However, since automatic translation of projects or news could potentially result in translations that go against the original intent, I decided to create buttons on two fixed pages to toggle between them.
I added an onClick property to the buttons and linked them to a function.
const displayString = (japaneseString: string, englishString: string) => {
return <>{usingJapanese ? japaneseString : englishString}</>;
};
I achieved this by inserting this into the rendering logic.
Positioning and Designing the Right Sidebar to Avoid Overlap with the Scrollbar
This was one of the points I personally struggled with. I had already decided to display related projects in the right sidebar of the project detail page and to provide a background color.
.sidebar {
position: fixed;
right: 0;
background-color: #fafafa;
/* Other properties described here */
}
While this works fine in some browsers (Firefox, Opera, Safari), in others, the scrollbar gets buried. Even if I set a value like right: 17px based on actual measurements, discrepancies occur due to zoom levels.
If the scrollbar isn't visible, users won't know if the page continues, leading to a decline in UX.
Therefore, I realized that I needed a mechanism to calculate the width of the scrollbar and shift the sidebar accordingly every time the window is resized. I made it a client component and implemented event listeners and functions within useEffect.
useEffect(() => {
// Calculate scrollbar width by actually generating an element
function getScrollbarWidth() {
const outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.overflow = "scroll";
document.body.appendChild(outer);
const inner = document.createElement("div");
outer.appendChild(inner);
const scrollbarWidth = outer.offsetWidth - inner.offsetWidth;
outer.parentNode?.removeChild(outer);
return scrollbarWidth;
}
// Update when resized
function updateScrollbarWidth() {
const width = getScrollbarWidth();
setScrollbarWidth(width);
const outerDiv = document.getElementById("top_main");
if (outerDiv) {
const scrollbarVisible = outerDiv.scrollHeight > outerDiv.clientHeight;
setScrollbarAppeared(scrollbarVisible);
}
}
updateScrollbarWidth();
window.addEventListener("resize", updateScrollbarWidth);
return () => {
window.removeEventListener("resize", updateScrollbarWidth);
};
}, []);
For the implementation, I used two useState hooks:
-
scrollbarWidth: The width of the scrollbar. -
scrollbarAppeared: Whether a scrollbar has appeared on the page.
scrollbarWidth
The calculation of the scrollbar width was performed using the following steps:
- Create a div element:
outer. - Edit styles to make the element invisible and ensure the scrollbar is always displayed within
outer. - Append
outerto the body. - Create a div element called
innerand make it a child ofouter. - The difference in
offsetWidthbetweenouterandinnerbecomes the scrollbar width.
scrollbarAppeared
Determining whether a scrollbar has appeared on the page was done with these steps:
- Get the scrollable element (main content):
outerDiv. - If retrieved, determine if the
scrollHeightof the main content is greater than itsclientHeight.
Once this is written, all that's left is to write the style property directly into the div element.
<div style={{ right: `${scrollbarAppeared ? scrollbarWidth : 0}px` }} />

In the case of Chrome (after offsetting)

In the case of Firefox (after offsetting)
Displaying Related Projects
Next is the content part of the right sidebar. Related projects were determined based on the following criteria:
- Whether the title partially matches.
- Whether any of the keywords partially match.
If even one of these conditions was met, it was considered a related project.
const filteredRelativeProject = projects.filter(
(item) =>
project?.tags.some(
(tag) =>
item.tags.some(
(itemTag) =>
tag.name !== "" &&
itemTag.name.toLowerCase().includes(tag.name.toLowerCase())
) || project?.title.toLowerCase().includes(item.title.toLowerCase())
) && project?.id !== item.id
);
Metadata Settings
In Next.js, you can configure elements within <head> by returning a Metadata type from the generateMetadata function.
I created SEO.tsx to handle the expansion of metadata generated on each page.
Metadata for Dynamically Generated Pages
Metadata is assigned using the specific project (or news) item hit from the project (or news) list.
export async function generateMetadata({
params,
}: {
params: { slug: string };
}): Promise<Metadata> {
const { project } = await getProject(params.slug);
if (!project)
return SEO({
title: "Undefined",
description: "No Project",
url: `https://sai.ac/project/${params.slug}`,
imageUrl: undefined,
});
else
return SEO({
title: project.title,
description: project.abstract,
url: `https://sai.ac/project/${params.slug}`,
imageUrl: undefined,
});
}
For pages not target for generation, they aren't necessarily redirected to a notFound page; the link remains, so I set the metadata as "Undefined".
Sitemap Creation
Since the sitemap is a file monitored by Google's crawler, I also want to include updates to news and projects.
In Next.js, when generating a sitemap from TypeScript, you place sitemap.tsx directly under the app directory.
I defined separate variables for static pages and dynamic pages.
(Supplement) Changing Display Text based on the OS
In the <input /> mentioned in Using the Enter Key for Searching, the placeholder displays "Tap to enter" or "Click to enter".
setIsUsingPhone(/iPhone|iPad|iPod|Android/i.test(navigator.userAgent));
The value is assigned directly as a boolean to the useState hook's setter. Since navigator is a client-specific interface, it is executed within useEffect.

Desktop version

Mobile version
(Supplement) Installing a "Back to Top" Button that Doesn't Reference the Body
In the pages created for this project, the scrollbar is uniformly configured to appear only below the header. (See image)

Scrollbar positioned below the header
While "Back to Top" buttons are common, I needed a different approach because I had to monitor the interior of a div element.
const containerRef = useRef(null);
I used the useRef hook and assigned it as follows:
<body>
{/* Preceding content omitted */}
<Header />
<main ref={containerRef} id="top_main">
{children}
{/* Footer is part of the scroll target */}
<Footer />
<ScrollToTopButton containerRef={containerRef} />
</main>
</body>
The key point is <main ref={containerRef}>, where the ref is attached to the main tag (the page's scrollable element).
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
const handleScroll = () => {
const scrollTop = containerRef.current.scrollTop;
// Do not show until scrolled down 300px
if (scrollTop > 300) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
containerRef.current.addEventListener("scroll", handleScroll);
return () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
containerRef.current.removeEventListener("scroll", handleScroll);
};
}, [containerRef]);
containerRef is the useRef hook passed via props. The appearance of the "Back to Top" button is managed by retrieving scrollTop and determining visibility based on the scroll amount.
Development (SCSS)
This is a part directly linked to UX. It is a section where you cannot let your guard down if you aim for improvement. For this project, I performed scratch development using SCSS for the styles.
I wanted to focus on visual guidance and ensuring that buttons and links are recognizable at a glance. I developed this project using rem as the base unit.
- Header height is 4rem
- Overflowing parts are clipped with
overflow: hidden;
Image and Animation Section on the Top Page
Instead of covering the entire screen (height: 100vh;), it is important to make users realize that they can scroll.
.img_box {
background-color: #e6e6e6;
width: 100%;
height: 30rem;
max-height: calc(100vh - 4rem);
// Omitted
}
It covers the full screen only when the height is very small.
Making All Text Animations Appear in the Same Position
.animation_box {
position: absolute; // Fix the position of the box containing animations
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: #232323;
z-index: 1500;
// Place all child div elements in the same location with the same size as animation_box
& > div {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
justify-content: center; // Center elements
align-items: center;
text-align: center;
display: flex;
flex-direction: column;
overflow: hidden;
// (Omitted)
}
// (Omitted)
}
After that, you can display them simply by adjusting the animation-delay. Finally, display: none; is executed with a delay to reveal the image behind it.
Bottom Buttons
These are the two buttons: the language switching button and the "Back to Top" button. Of course, they are aligned at the bottom, but the issue is how much to float them.
Initially, I used about 1rem, but when opening as a PWA on an iPhone 11, the display was considerably cut off by the frame. Following this result, it became 2rem.
Search Buttons for Each Member
When the screen width is not mobile-sized, the button width is width: 2.5rem;. However, I set it to width: 3.6rem; specifically for mobile widths.
This is because problems arise with hovering-type scrollbars.
Since the right edge is the scrollbar area, the display overlaps during scrolling. This creates a risk of the user accidentally touching the scrollbar, which effectively reduces the touchable area of the button. To counter this, I increased the button area for narrow widths.
(Supplement) Issues with Fixing Section Titles using position: fixed;
During this implementation, the compatibility between h tags using position: fixed; and in-page links using id was very poor. While jumping from top to bottom worked, jumping from bottom to top did not. Please refer here for the resolution of this issue.
Displaying the Table of Contents from the Top
I created a table of contents menu that doesn't follow the header but always stays at the top left during scrolling.
.l_sidebar {
width: 3.5rem;
height: 3.5rem;
background-color: $c-y_list_bg;
margin-top: 1rem;
top: 1rem;
left: 1rem;
position: sticky;
overflow: visible;
// Omitted
}
By setting overflow: visible, protruding elements are also displayed, allowing for expanded rendering. Since this design involves changing the left sidebar with a responsive design, this setting was necessary.
The height of the menu was adjusted by subtracting 12rem from the maximum height to prevent the header and footer from overlapping.
&.open {
height: auto;
max-height: calc(100vh - 12rem);
}
Release and Operation
I linked the GitHub repository to Vercel. When applying patches, I create a branch and use the preview feature, which allows me to check everything except for OpenGraph. Once I confirm there are no issues, I merge the changes.
The cache revalidation times for operation were set as follows:
- Members: 6 hours
- Projects: 1 hour
- News: 5 minutes
- Awards: 8 hours
Updates have already been confirmed, and the site is currently being operated primarily by the faculty.
Points of Caution
I will also describe several points I kept in mind during development.
Character Limit in Spreadsheets
There is a limit of 50,000 characters per cell. While this is not a number easily exceeded, it is something to watch out for when inserting <svg> tags.
I also checked the GAS response limits. Based on the site mentioned in (Supplement) Caching Countermeasures, I suspect it might hit the URL Fetch POST size limit. Since it is listed as 50 MB per action, I believe we should be fine as long as we don't exceed this value.
Bringing Images Directly from Google Drive
For this project, I set the image source to a directory on a server contracted by the laboratory. Although there are supposedly methods to use shared links from Google Drive, I decided against it for reasons such as terms of service.
Points of Focus and Difficulties
Points of Focus (Efforts)
I intended to be thorough with the CSS (SCSS). Button size design and screen occupancy ratios directly affect usability and user satisfaction. While functionality is certainly crucial, I felt that since this is a page people will look at, it needs to behave politely.
In the design of HTML elements, I prioritized how many steps it takes to access the desired functionality. I aimed to make the step distance as small as possible while contemplating which designs and layouts would allow even first-time visitors to reach their destination quickly.
I made adjustments by asking people around me what content they would likely view next after looking at a certain section. I would like to express my gratitude to those who shared their opinions.
Difficulties
Caching and the sidebar offset remain the most memorable challenges.
While implementing article updates and deploying to a test environment, I ran into a situation where articles wouldn't update for some reason. Being unfamiliar with App Router, I struggled to solve it while reading the documentation. Halfway through, as a compromise, I was performing updates by purging the Data Cache on Vercel and redeploying, but I felt the cost of updating was very high. I eventually solved it, but if I hadn't, I was seriously considering Fastly.
The scrollbar is a valuable indicator that a web page is scrollable, so I wanted to make the most of it.
Final Thoughts
This was my fourth time building a site using Next.js, and my development speed has become stable.
I feel that having a system where you can always hear third-party opinions is beneficial for building a site that prioritizes the UX (User Experience) for both users and administrators. Thank you very much.
Discussion